سؤال

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

هل كانت مفيدة؟

المحلول 2

There is no built-in function to do this. Writing a streaming function in C# to do it would be trivial (read 2 chars, emit a byte). You can either use a SQLCLR function to do it inside the engine, or you can do it in the client side. IF the input is large is arguably better to do it in the client side to avoid memory overload.

Here's an example of streaming conversion (no omptimizations, but highlights the important of not converting a string into 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);
                }
            }
        }
    }
}

نصائح أخرى

Here is example of T-SQL code to convert your string back to varbinary(max)

declare @hexstring varchar(max)='abcedf012439112200AABBCCFF';
set @hexstring = '0x'+@hexstring;
select CONVERT(varbinary(max), @hexstring, 1);

If I understand correctly you want to convert every 2 characters to a byte, this can be achieved using the already answered question.

Convert hex string to byte array also How to Convert Hex String to Byte[]

Hope it helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top