当前位置: 代码迷 >> Sql Server >> 分享:实现其他进制数与二进制数的转化解决方法
  详细解决方案

分享:实现其他进制数与二进制数的转化解决方法

热度:46   发布时间:2016-04-27 17:58:26.0
分享:实现其他进制数与二进制数的转化
SQL code
/*====================================================*/ 
-- Author: Ken Wong
-- Create date: 2010-01-07 23:01:08
-- Description: 将其他进制数转化为二进制数
-- select dbo.convertobinary('18',10)

/*====================================================*/
[email protected] 要转化的数值 @type原进制类型
create function dbo.convertobinary (@number varchar(30),@type int)
returns varchar(30)
as
begin
declare @return varchar(30),@i int
select @return='',@i=1
if @type=2
begin
select @[email protected]
end
else if @type=8
begin
while @i <=len(@number)
begin
select @[email protected]+case substring(@number,@i,1) when '0' then '000'
when '1' then '001' when '2' then '010' when '3' then '011'
when '4' then '100' when '5' then '101' when '6' then '110'
when '7' then '111' end
select @[email protected]+1
end
end
else if @type=10
begin
while cast(@number as int)>=1
begin
select @return=ltrim(cast(@number as int)%2)[email protected]
select @number=ltrim((cast(@number as int)-cast(@number as int)%2)/2)
end
end
else if @type=16
begin
while @i <=len(@number)
begin
select @[email protected]+case substring(@number,@i,1) when '0' then '0000'
when '1' then '0001' when '2' then '0010' when '3' then '0011'
when '4' then '0100' when '5' then '0101' when '6' then '0110'
when '7' then '0111' when '8' then '1000' when '9' then '1001'
when 'A' then '' when 'B' then '1011' when 'C' then '1100'
when 'D' then '1101' when 'E' then '1110' when 'F' then '1111' end
select @[email protected]+1
end
end
return @return
end




------解决方案--------------------
给你几个,你看看.
SQL code
--十进制转为十六进制DECLARE @binary varbinary(255), @str_return varchar(255) SELECT @binary = CONVERT(varbinary(255),29327795562177529) EXEC master.dbo.xp_varbintohexstr @binary, @str_return OUTPUT SELECT 结果 = reverse(@str_return)/*结果__________________________008613974878369F10000011x0*/--十六进制转为十进制CREATE FUNCTION dbo.f_hex_dec(@s varchar(16))RETURNS bigintASBEGIN--作者:pbsql--参数不得含'0'~'9'、'a'~'f'、'A'~'F'之外的任意字符(首尾空格除外),否则返回0  DECLARE @i int,@result bigint  SELECT @i=0,@result=0,@s=RTRIM(LTRIM(UPPER(REVERSE(@s))))  WHILE @i<LEN(@s)  BEGIN    IF SUBSTRING(@s,@i+1,1) not between '0' and '9' and SUBSTRING(@s,@i+1,1) not between 'A' and 'F'    BEGIN      SELECT @result=0      break    END    SELECT @[email protected]+(CHARINDEX(SUBSTRING(@s,@i+1,1),'0123456789ABCDEF')-1)*POWER(16,@i),@[email protected]+1  END  RETURN @resultENDGO
------解决方案--------------------
jf,收藏了,LZ结贴吧
------解决方案--------------------
UP
------解决方案--------------------
jf.
------解决方案--------------------
好好学习,天天向上
------解决方案--------------------
roy的博客也有相关的话题:http://blog.csdn.net/roy_88/archive/2007/11/13/1882106.aspx
------解决方案--------------------
  相关解决方案