Convert integer to hex and hex to integer
To convert an integer to hex, use the function CONVERT(VARCHAR(8), YourInteger, 2)
. For converting a hex to integer, use CONVERT(INT, YourHexNumber)
.
This quick answer assumes we are working with SQL Server 2008 or later. Other systems might have different methods for conversion.
Getting used to SQL's CONVERT quirks
Dealing with '0x' in Hex Strings
If your hexadecimal string starts with '0x', remember to use style 1 in your CONVERT
function. SQL Server can be a little stubborn about these things!
Handling Hex Strings without '0x'
When a 0x
prefix is absent, use style 2. Keep in mind, SQL Server likes its digits in pairs, so pad with zeros accordingly. No one likes odd ones out!
Making pretty hex strings with FORMAT
From SQL Server 2012 and onward, life got a little easier because we now have the FORMAT
function.
Advanced methods and precautions
Use of the good old fn_varbintohexstr function
Alternatives do exist in some older systems; you might encounter the legacy function master.dbo.fn_varbintohexstr
:
Be mindful though, this function may not be around forever!
Understanding differences between SQL Server and Excel
Let's acknowledge that while Excel offers straightforward DEC2HEX and HEX2DEC functions, SQL Server requires a different approach.
Type your data right!
Use VARBINARY
for hex representation and either VARCHAR
or INT
for decoded values, ensuring the data types play well in your usage context.
Beware of odd ones out
Make sure your hex strings always contain an even number of hex digits, or SQL Server might throw a tantrum.
Was this article helpful?