10

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?

JMP
  • 7,734
  • 6
  • 33
  • 34

3 Answers3

5

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.

ladenedge
  • 13,197
  • 11
  • 60
  • 117
  • Removing the `0x` from the string is a subtle but important difference between the data that would be copied and the example here. Without doing that you will get `xsd:hexBinary` errors – StingyJack Jun 16 '20 at 19:37
  • I'm getting `xsd:hexBinary invalid` errors even after removing the `0x`. Edit: removing one character from the end (to make the length even, I suppose) fixed it. – georgiaboy82 Jul 06 '20 at 18:14
  • Is there a way to do this in .NET Core? I can't find an analogous library – codeMonkey Aug 12 '22 at 23:12
4

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.

full-stack
  • 553
  • 5
  • 20
0

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.

codeMonkey
  • 4,134
  • 2
  • 31
  • 50