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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With