Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Convert Hex to decimal

Tags:

tsql

I try to use TSQL and I get some problem to convert hex to decimal when the value is inside a variable.

My code is:

SET @hex = SUBSTRING(@x,1,2) --give 1e
SET @hex = '0x' + @hex
SELECT CAST (@hex AS int)

I get the error that the conversion failed when converting the varchar value to int

I don't know what it's wrong and so far I can't find solution

Any idea? Thanks

like image 430
usertfwr Avatar asked Dec 25 '22 19:12

usertfwr


1 Answers

This works (for SQL Server 2008 or later):

declare @hex varchar(316)
SET @hex = '1e' --SUBSTRING(@x,1,2) --give 1e
SET @hex = '0x' + @hex
SELECT CONVERT(int,CONVERT (binary(1),@hex,1))

See "Binary Styles" on the CAST and CONVERT page.

like image 131
Damien_The_Unbeliever Avatar answered Jun 19 '23 00:06

Damien_The_Unbeliever