Technical Article

Convert from hexadecimal to binary -and vice versa

,

Converts data from hex to binary and vise-versa.

CREATE FUNCTION dbo.cHex2Bin 
(
@hex varchar(50) 
)

RETURNS varchar(200)

AS

BEGIN

set @hex=replace (@hex,'1','0001')
set @hex=replace (@hex,'2','0010')
set @hex=replace (@hex,'3','0011')
set @hex=replace (@hex,'4','0100')
set @hex=replace (@hex,'5','0101')
set @hex=replace (@hex,'6','0110')
set @hex=replace (@hex,'7','0111')
set @hex=replace (@hex,'8','1000')
set @hex=replace (@hex,'9','1001')
set @hex=replace (@hex,'A','1010')
set @hex=replace (@hex,'B','1011')
set @hex=replace (@hex,'C','1100')
set @hex=replace (@hex,'D','1101')
set @hex=replace (@hex,'E','1110')
set @hex=replace (@hex,'F','1111')

--get rif od leading 0

while charindex('x0','x'+@hex)>0 
set @hex=replace ('x'+@hex,'x0','')

RETURN @hex
END
GO 

--Convert from binary to hexadecimal 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE FUNCTION cBin2Hex 
(
@Hex varchar(100)
)
RETURNS varchar(50)
AS
BEGIN
DECLARE @bin as varchar(50)
select @bin=''
set @Hex='000'+@Hex
while len(@HEx)>3

begin
select @bin= case right(@hex,4)
   when '1111' then 'F'
   when '1110' then 'E'
   when '1101' then 'D'
   when '1100' then 'C'
   when '1011' then 'B'
   when '1010' then 'A'
   when '1001' then '9'
   when '1000' then '8'
   when '0111' then '7'
   when '0110' then '6'
   when '0101' then '5'
   when '0100' then '4'
   when '0011' then '3'
   when '0010' then '2'
   when '0001' then '1'
   when '0000' then '0'
end +@bin

set @hex=left(@hex,Len(@hex)-4)

end
RETURN @bin

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

Rate

5 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (1)

You rated this post out of 5. Change rating