JMP
JMP

Reputation: 7834

Convert SQL Binary to byte array

Given some data stored in a SQL binary field:

0x83C8BB02E96F2383870CC1619B6EC...

I'd like to convert it into a byte array, but it doesn't seem like I can just cast this directly into a byte like so:

byte[] someBytes = (byte) 0x83C8BB02E96F2383870CC1619B6EC...;

What am I missing here?

Upvotes: 10

Views: 16013

Answers (3)

codeMonkey
codeMonkey

Reputation: 4815

Stolen from this answer:

Remove the 0x from the beginning of your data and create a string:

var stringHex = "83C8BB02E96F2383870CC1619B6EC...";

Then convert to byte[] with this method:

byte[] myArray = Enumerable.Range(0, stringHex.Length / 2)
                           .Select(x => Convert.ToByte(stringHex.Substring(x * 2, 2), 16))
                           .ToArray();

I had to use this method because my data was too long, so I was getting errors about Int32 and Int64 overflow.

Upvotes: 0

full-stack
full-stack

Reputation: 553

Your casting is wrong.

byte[] someBytes = (byte[]) 0x83C8BB02E96F2383870CC1619B6EC...;

I had the same problem and I stumbled across this question. After further research I tried casting like the above and it worked.

Upvotes: 4

ladenedge
ladenedge

Reputation: 13419

The data stored in the SQL field is in binary. The '0x83..' string you quoted is just a hexadecimal representation of that binary data.

If you just want to copy/paste the hexadecimal data into your C# code (as you seem to have written), then you'll need to convert it from hexadecimal to binary. .NET provides a (rather obscure) class for this sort of thing:

using System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary

public byte[] ToBytes(string hex)
{
    var shb = SoapHexBinary.Parse(hex);
    return shb.Value;
}

public void TestConvert()
{
    byte[] someBytes = ToBytes("83C8BB02E96F2383870CC1619B6EC");
}

If your binary data is coming from your database in a different form than a copy/pasted string, you'll need to provide more information about your setup.

Upvotes: 5

Related Questions