Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a SQL func to convert a decimal no. to Hex ? 1

Status
Not open for further replies.

calvinsinger

Programmer
Oct 21, 2002
22
US
Is there a SQL func to convert a decimal no. to Hex ?Provided by the SQL server, or does one have to write one of
his own.

Thanks
 
You can try convert(varbinary,@int_variable). It does conversion for numbers with decimal places also but the output may need to be interpretted properly. For whole values, it works properly.
RT
 
Thanks for your response. Meanwhile I ended up writing
my own functions to convert Binary to Hex, & convert integers to Hex

Calvin


CREATE FUNCTION Bin2Hex (@sBin varchar(512))
Returns varchar(128)
AS
BEGIN
Declare @i int, @nDec int
set @sBin = REPLICATE('0', 4-LEN(@sBin)%4) + @sBin
--Add zero to complete Byte

set @i = 1
set @nDec = 0

While @i <= LEN(@sBin)
BEGIN
set @nDec = @nDec + CAST(SUBSTRING(@sBin, LEN(@sBin)-@i+1, 1) as int) * POWER(2, (@i-1))
set @i = @i + 1
END

Return dbo.Dec2Hex(@nDec)
END


drop FUNCTION dbo.Dec2Hex
--Only run this func for integers not floats
CREATE FUNCTION dbo.Dec2Hex (@nDec int)
Returns varchar(128)
AS

BEGIN
Declare @rmndr int, @HexStr varchar(128), @rmndrHex varchar(128)

set @HexStr = ''
set @rmndrHex = ''
set @rmndr = 0

While @nDec <> 0
BEGIN
set @rmndr = @nDec % 16
set @nDec = (@nDec - @rmndr)/16

if @rmndr <= 9
BEGIN
set @rmndrHex = CAST(@rmndr as varchar(128))
END
else
if @rmndr = 10
BEGIN
set @rmndrHex = 'A'
END
else
if @rmndr = 11
BEGIN
set @rmndrHex = 'B'
END
else
if @rmndr = 12
BEGIN
set @rmndrHex = 'C'
END
else
if @rmndr = 13
BEGIN
set @rmndrHex = 'D'
END
else
if @rmndr = 14
BEGIN
set @rmndrHex = 'E'
END
else
if @rmndr = 15
BEGIN
set @rmndrHex = 'F'
END

set @HexStr = @rmndrHex + @HexStr
END
Return (@HexStr)
END
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top