0

Apologies if this is a duplicate and I'm terrible at searching. I'll post a few of the things I tried below.

I'm using Entity Framework to pull a varbinary column from a SQL Server database. Entity Framework returns a byte[].

When I query the database using SSMS, this is what I get (and what I'm trying to get in C#): 0x540FA51A000706010096000B64FFAEC1

Database encoding is UTF8. Thanks in advance.

Here are a few of the things I've tried:

public static string ByteArrayToString(byte[] ba)
{
    StringBuilder hex = new StringBuilder(ba.Length * 2);

    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);

    return hex.ToString();
}

public static string ByteArrayToString(byte[] ba)
{
    if (BitConverter.IsLittleEndian)
        Array.Reverse(ba);

    string hex = BitConverter.ToString(ba);
    return hex.Replace("-", "");
}

private static string ByteArrayToHex(byte[] barray)
{
    char[] c = new char[barray.Length * 2];
    byte b;

    for (int i = 0; i < barray.Length; ++i)
    {
        b = ((byte)(barray[i] >> 4));
        c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
        b = ((byte)(barray[i] & 0xF));
        c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
    }

    return new string(c);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Han
  • 49
  • 1
  • 3
  • 1
    Possible duplicate of [How do you convert a byte array to a hexadecimal string, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa) – ProgrammingLlama Mar 08 '19 at 02:27
  • Not a duplicate... nothing in that post helped. The top comment from that post was listed under "things I've tried" – Han Mar 08 '19 at 02:36
  • 1
    Perhaps you need to explain why they don't work then? They work fine for me: [example](https://rextester.com/VAUX29254). – ProgrammingLlama Mar 08 '19 at 02:37
  • Sorry.. I would if I knew. I'm just getting an empty string back. I think it has something to do with pulling the byte array from MSSQL. – Han Mar 08 '19 at 02:50
  • If you're getting an empty string back, then my conclusion is that you're passing a 0-length byte array in. – ProgrammingLlama Mar 08 '19 at 02:52
  • Checked that much, it's not 0 bytes. – Han Mar 08 '19 at 03:02
  • Please make sure you assign the value to a byte array before checking (e.g. `byte[] a = value`). I think you need to provide a [mcve] for us to help you, because what you're describing at the moment (a non-zero length byte array producing an empty string from that method) doesn't seem possible. – ProgrammingLlama Mar 08 '19 at 03:22
  • To be clear: I'm not saying that it isn't possible that there's an issue elsewhere, but the code to convert from byte to hex isn't the problem. – ProgrammingLlama Mar 08 '19 at 04:58

0 Answers0