3

I have a string with a hexadecimal value, as an example, like so: "AD5829FC..." which is a varbinary I took and saved in hexadecimal to a text file. The thing is, I need to get this back to a varbinary by running an insert query through C# and SQL Server 2008.

How do I get it back to its original format. I am currently using a SQL CAST like so:

CAST('HEX VALUE' AS varbinary(MAX))

NOTE: I need to save it to the text file like I just showed it so that the CSV doesn't get any \n or comma characters from a sequence in the hexadecimal

4

3 回答 3

4

这是将字符串转换回 varbinary(max) 的 T-SQL 代码示例

declare @hexstring varchar(max)='abcedf012439112200AABBCCFF';
set @hexstring = '0x'+@hexstring;
select CONVERT(varbinary(max), @hexstring, 1);
于 2013-07-16T14:20:56.030 回答
1

没有内置函数可以做到这一点。在 C# 中编写一个流式函数来做到这一点很简单(读取 2 个字符,发出一个字节)。您可以使用 SQLCLR 函数在引擎内部执行此操作,也可以在客户端执行此操作。如果输入很大,可以说最好在客户端执行,以避免内存过载。

这是流转换的示例(没有优化,但强调了将 a 转换string为 a的重要性byte[]):

namespace hex2bin
{
    class Program
    {
        public static void hex2bin(TextReader sin, BinaryWriter sout)
        {
            char[] block = new char[2];
            bool eof = false;
            do
            {
                int chars = sin.ReadBlock(block, 0, 2);
                switch (chars)
                {
                    case 0:
                        eof = true;
                        break;
                    case 1:
                        // Input is odd length, invalid case
                        throw new Exception("Invalid input");
                    case 2:
                        string sblock = new String(block);
                        byte b = Convert.ToByte(sblock, 16);
                        sout.Write(b);
                        break;
                }
            } while (!eof);

        }

        static void Main(string[] args)
        {
            using (StringReader sr = new StringReader("AD5829FC"))
            {
                using (BinaryWriter bw = new BinaryWriter(new MemoryStream()))
                {
                    hex2bin(sr, bw);
                }
            }
        }
    }
}
于 2013-07-16T13:51:44.380 回答
1

如果我理解正确,您想将每 2 个字符转换为一个字节,这可以使用已经回答的问题来实现。

将十六进制字符串转换为字节数组以及如何将十六进制字符串转换为字节[]

希望能帮助到你。

于 2013-07-16T13:56:55.510 回答