如何在SQL Server中将字符编码的二进制字符串转换为十六进制?

时间:2009-07-02 17:29:33

标签: sql sql-server

我正在尝试使用VARCHAR(MAX)中的数据,如下所示: “00001001010001010111010101 ......”等。

然后将其编码为十六进制,以便更有效地返回客户端。

有可能这样做吗?直接或者在调用master.dbo.fn_varbintohexstr之前将字符串转换为真正的二进制列?

举个例子,给出字符串:

0000100101000101011101011110

我们最终应该:

0000 = 0
1001 = 9
0100 = 4
0101 = 5
0111 = 7
0101 = 5
1110 = E

094575E。

或者如果有一种更有效的方法(直接读取二进制文件?)那就更好了。最好使用SQL Server 2000兼容的解决方案。

4 个答案:

答案 0 :(得分:4)

鉴于您之前的问题,您将生成此字符串作为另一个查询的一部分。为什么在地球上你生成一串1和0,你可以将它们乘以适当的2的幂来从它们中取出INT而不是字符串?从INT转换为十六进制字符串是微不足道的。

答案 1 :(得分:1)

您始终可以使用SUBSTRING将字符串拆分为4个字符组(从结尾开始!),并将4个字符组转换为十六进制数字,例如。在大CASE声明中'0011'到'3'。 CASE中只有16个开关案例,因此更易于管理。但是你得到的只是减少了4倍的长度,不确定是否值得(显着)服务器开销只是为了减少流量。

答案 2 :(得分:0)

另一种解决方案可能是使用您喜欢的.NET语言实现用户定义的函数

答案 3 :(得分:-1)

您是否在寻找类似的内容:http://support.microsoft.com/kb/104829

这是因为链接已经死亡:

    create procedure sp_hexadecimal
     @binvalue varbinary(255)
   as
   declare @charvalue varchar(255)
   declare @i int
   declare @length int
   declare @hexstring char(16)

   select @charvalue = '0x'
   select @i = 1
   select @length = datalength(@binvalue)
   select @hexstring = "0123456789abcdef"

   while (@i <= @length)
   begin

     declare @tempint int
     declare @firstint int
     declare @secondint int

     select @tempint = convert(int, substring(@binvalue,@i,1))
     select @firstint = floor(@tempint/16)
     select @secondint = @tempint - (@firstint*16)

     select @charvalue = @charvalue +
       substring(@hexstring, @firstint+1, 1) +
       substring(@hexstring, @secondint+1, 1)

     select @i = @i + 1

   end

   select 'sp_hexadecimal'=@charvalue
相关问题