十进制转二进制和十六的两个函数
A.调用测试:
Update MySheet1 set 二进制= dbo.inttobit(十进制)
Update MySheet2 set 十六进制= dbo.inttohex(十进制)
B.函数内容
--十进制转二进制函数
CREATE FUNCTION dbo.inttobit (@number int)
returns varchar(100)
as
BEGIN
DECLARE @i int
DECLARE @j float
DECLARE @m int
DECLARE @OUT1 varCHAR(1)
DECLARE @OUT2 varchar(20)
SET @i=@number
set @out2=' '
WHILE @i>=1
BEGIN
SET @j=@i/2
SET @m=@i%2
SET @i=floor(@j)
SET @OUT1=cast(@m as char(1))
SET @OUT2=@OUT1+@OUT2
END
RETURN @OUT2
END
--十进制转十六进制函数
CREATE function dbo.inttohex(@i int)
returns varchar(15)
begin
--declare @i int
--set @i=11259375
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