Sql server实现十六进制和十进制的转换

时间:2020-12-08 00:56:38
写着玩玩

-- 十六进制转十进制
Create    function hextoint(@h varchar(8))
returns bigint
begin

-- select dbo.hextoint(1705)
declare @r bigint 
set @r=0

declare @i bigint
set @i=1

while @i<=len(@h)
begin
set @r=@r+

convert(int,
(
case
when substring(@h,@i,1)<='9' then substring(@h,@i,1)
when substring(@h,@i,1)<='A' then '10'
when substring(@h,@i,1)<='B' then '11'
when substring(@h,@i,1)<='C' then '12'
when substring(@h,@i,1)<='D' then '13'
when substring(@h,@i,1)<='E' then '14'
when substring(@h,@i,1)<='F' then '15'
end
))
*power(16,len(@h)-@i)

set @i=@i+1

end

return @r


end
 

----------
--十进制转十六进制
Create     function inttohex(@i bigint)
returns varchar(15)
begin


--declare @i bigint
--set @i=3063457542

declare @r varchar(10) 
set @r=''


while @i/16>0
begin


set @r=
(case
when (@i % 16)<=9 then convert(varchar(1),@i % 16)
when (@i % 16)=10 then 'A'
when (@i % 16)=11 then 'B'
when (@i % 16)=12 then 'C'
when (@i % 16)=13 then 'D'
when (@i % 16)=14 then 'E'
when (@i % 16)=15 then 'F'
end)
+@r

--select @r,@i

set @i=@i/16


end

--select @r,@i


if @i>0
set @r=(case
when (@i % 16)<=9 then convert(varchar(1),@i % 16)
when (@i % 16)=10 then 'A'
when (@i % 16)=11 then 'B'
when (@i % 16)=12 then 'C'
when (@i % 16)=13 then 'D'
when (@i % 16)=14 then 'E'
when (@i % 16)=15 then 'F'
end)+@r

-- select @r


return @r


end