Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL Binary to byte array

Tags:

c#

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?

like image 340
JMP Avatar asked Oct 12 '10 15:10

JMP


2 Answers

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.

like image 95
ladenedge Avatar answered Sep 23 '22 13:09

ladenedge


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.

like image 42
full-stack Avatar answered Sep 21 '22 13:09

full-stack