0

Looking to convert an integer to the hex string equivalent using TSQL

1 =    1
10 =   A
100 = 64
1000 = 3E8

etc.

SO FAR the solution seems to be

DECLARE @str VARCHAR(10)
SELECT @str = sys.fn_varbintohexstr(CONVERT(VARBINARY, @num))
IF @num < 16
   SELECT @str = RIGHT(@str, 1)
ELSE IF @num < 256
   SELECT @str = RIGHT(@str, 2)
ELSE IF @num < 4096
   SELECT @str = RIGHT(@str, 3)
ELSE -- and so on
   SELECT @str = RIGHT(@str, 4)

RETURN @str

but someone this seems a little klutzy, is there a better way ?

Kumar
  • 10,997
  • 13
  • 84
  • 134
  • @IlyaBursov, this Q is for int to hex STRING, that too WITHOUT 0x or the leading ZEROS – Kumar Oct 25 '13 at 04:32
  • just look at other solutions on link I've provided – Iłya Bursov Oct 25 '13 at 04:41
  • @IlyaBursov already did that, they don't address part 2 of this question, the klutzy one ! – Kumar Oct 25 '13 at 13:51
  • check `SELECT dbo.ToHex(4095) --> FFF CREATE FUNCTION ToHex(@value int) RETURNS varchar(50) AS BEGIN DECLARE @seq char(16) DECLARE @result varchar(50) DECLARE @digit char(1) SET @seq = '0123456789ABCDEF' SET @result = SUBSTRING(@seq, (@value%16)+1, 1) WHILE @value > 0 BEGIN SET @digit = SUBSTRING(@seq, ((@value/16)%16)+1, 1) SET @value = @value/16 IF @value 0 SET @result = @digit + @result END RETURN @result END GO` this is from link above – Iłya Bursov Oct 25 '13 at 15:18

0 Answers0