Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to hex and hex to integer

So I have this query working (where signal_data is a column) in Sybase but it doesn't work in Microsoft SQL Server:

HEXTOINT(SUBSTRING((INTTOHEX(signal_data)),5,2)) as Signal 

I also have it in Excel (where A1 contains the value):

=HEX2DEC(LEFT(DEC2HEX(A1),LEN(DEC2HEX(A1))-2)) 

Does anyone know how I would do this in SQL Server?

like image 815
Nick Sinas Avatar asked Mar 31 '09 20:03

Nick Sinas


People also ask

How do you convert hex to integer?

To convert a hexadecimal to a decimal manually, you must start by multiplying the hex number by 16. Then, you raise it to a power of 0 and increase that power by 1 each time according to the hexadecimal number equivalent.

Which method converts an int value into its equivalent hexadecimal?

An integer can be converted to a hexadecimal by using the string. ToString() extension method.

How do you convert int to hex in python?

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do you convert a decimal number to hexadecimal?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.


2 Answers

Convert INT to hex:

SELECT CONVERT(VARBINARY(8), 16777215) 

Convert hex to INT:

SELECT CONVERT(INT, 0xFFFFFF) 

Update 2015-03-16

The above example has the limitation that it only works when the HEX value is given as an integer literal. For completeness, if the value to convert is a hexadecimal string (such as found in a varchar column) use:

-- If the '0x' marker is present: SELECT CONVERT(INT, CONVERT(VARBINARY, '0x1FFFFF', 1))  -- If the '0x' marker is NOT present: SELECT CONVERT(INT, CONVERT(VARBINARY, '1FFFFF', 2)) 

Note: The string must contain an even number of hex digits. An odd number of digits will yield an error.

More details can be found in the "Binary Styles" section of CAST and CONVERT (Transact-SQL). I believe SQL Server 2008 or later is required.

like image 153
Bill Karwin Avatar answered Sep 22 '22 22:09

Bill Karwin


Actually, the built-in function is named master.dbo.fn_varbintohexstr.

So, for example:

SELECT 100, master.dbo.fn_varbintohexstr(100) 

Gives you

100 0x00000064

like image 25
justinpitts Avatar answered Sep 23 '22 22:09

justinpitts