Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

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

HexToInt

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: 104 | Views in the last 30 days: 2
 
Related Articles
FORUM

Digit by digit subtraction

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

FORUM

Subtracting From SUm

Total a Sum Then subtract from it

ARTICLE

Digital Storage

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

FORUM

SQL Subtraction - Seperate rows

Require SQL syntax to show subtraction of row data

SCRIPT

Integer left and right shift

3 functions that implement the left (<<), right (>>) and unsigned right (>>>) shift operators, commo...

Tags
miscellaneous    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones