Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)


By Aaron West,

Challenged by Hans Lindgren's stored procedures of the same name, I created this. Note that it produces strange results on non-hexadecimal strings, overflows at 0x80000000, and could have issues with byte-ordering on some architectures.

How does it work? Well, the distance between one after '9' (':') and 'A' is 7 in ASCII. Also, if I subtract 48 from an upper-cased hex-digit, digit & 16 will always be equal to 16. So I can mask that bit out, shift it down 4 bits (/16), multiply by 7, subtract from the original value, and come up with a value from 0 to 15. This can be done on all 8 digits in parallel, as you can see below.

I use CAST(CAST('1234ABCD' AS BINARY(8))AS BIGINT) to put the hex value 1234ABCD into a number I can manipulate, then subtract the value '00000000' (CAST(0x3030303030303030 AS BIGINT)), then mask out the hex overflow bits, shift right, multiply by 7, subtract to make the values 0x010203040A0B0C0D, then I shift the nybbles into the proper places and add.

Total article views: 112 | Views in the last 30 days: 1
Related Articles

Digit by digit subtraction

Hi All, I am a software programmer from India. I have 2 strings lets say str1 = '3456' str2 = '3754'...


Subtracting From SUm

Total a Sum Then subtract from it


Digital Storage

Digital technologies have made the transfer of information easier than ever, but what about it's lon...


SQL Subtraction - Seperate rows

Require SQL syntax to show subtraction of row data


Using Mod to Generate Work Shifts

A short story on using the mod function to a shifting query.