3

How can i convert a hex string in SQL Server to binary?

Better yet, how can i convert a hex string in SQL Server to an integer?

The problem is that every existing answer on Stackoverflow assumes SQL Server 2008.

Failed attempts

Edit

...yes 2005 has varbinary. Even 2000 has varbinary:

SELECT name, xtype FROM systypes WHERE name LIKE '%binary%'; 
SELECT @@version;

name       xtype
---------  -----
varbinary  165
binary     173

(No column name)
---------------------------------
Microsoft SQL Server  2000 - 8.00.2039 (Intel X86) 
May  3 2005 23:18:38 
Copyright (c) 1988-2003 Microsoft Corporation
Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)

Even SQL Server 6.5 has varbinary. *(archive)*Interesting, and typical SO fashion, to try to circumvent the question rather than answer it.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219

2 Answers2

1

Works for values that can be represented as a bigint

DECLARE @Hex VARCHAR(10)='0x3078'
DECLARE @DecValue BIGINT=0
DECLARE @Power TINYINT = 0

SET @Hex=REVERSE(REPLACE(@Hex,'0x',''))
WHILE LEN(@Hex)>0
BEGIN
    SET @DecValue=@DecValue+(POWER(16,@Power)*CONVERT(TINYINT,LEFT(@Hex,1)))
    SET @Power=@Power+1
    SET @Hex=RIGHT(@Hex,LEN(@Hex)-1)
END

SELECT @DecValue AS [Decimal value]
UnhandledExcepSean
  • 12,504
  • 2
  • 35
  • 51
1

SQL Server 2005 had a function master.sys.fn_varbintohexstr() (apparently in SQL Server 2000 it was called dbo.fn_varbintohexstr) to convert binary to string.

Searching for this function name brings up answers for converting hex strings to binary, such as this SO answer, or Social MSDN (useful code, but lots of dead links), or this MSDN blog using XQuery to parse a hex string.

devio
  • 36,858
  • 7
  • 80
  • 143