tags:

views:

11667

answers:

8

How do i convert a byte[] to a string, every time i attempt it i get System.Byte[] instead of the value.

Also How do i get the value in Hex instead of a decimal?

A: 

You have to know the encoding of the string represented in bytes, but you can say System.Text.UTF8Encoding.GetString(bytes) or System.Text.ASCIIEncoding.GetString(bytes). (I'm doing this from memory, so the API may not be exactly correct, but it's very close.)

For the answer to your second question, see this question.

Gregory Higley
+6  A: 

Well I don't convert bytes to hex often so I have to say I don't know if there is a better way then this, but here is a way to do it.

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
    sb.Append(b.ToString("X2"));

string hexString = sb.ToString();
Quintin Robinson
Looks about right. This really seems like something that should be in the framework, I swear people are always looking for a built in way to do this. Not sure why there isn't something already there. Oh well.
TJB
There is a built in way to do this, in the BitConverter class.
Guffa
Specify the capacity for the StringBuilder as myByteArray.Length*2 so that it doesn't have to reallocate during the loop.
Guffa
A: 

As others have said it depends on the encoding of the values in the byte array. Despite this you need to be very careful with this sort of thing or you may try to convert bytes that are not handled by the chosen encoding.

Jon Skeet has a good article about encoding and unicode in .NET. Recommended reading.

Ash
+3  A: 

Hex, Linq-fu:

string.Join("",ba.Select(b => b.ToString("X2")).ToArray())
Michael Buen
Michael, you need a .ToArray() on the Select, otherwise (as presented) you get a {System.Linq.Enumerable.WhereSelectArrayIterator<byte,string>} which String.Join cast to a String[].
Aussie Craig
You can use more clean solution with Concat.String.Concat(ba.Select(b => b.ToString("X2"))
Tomáš Linhart
@Tomáš Linhart: Thanks! :-)
Michael Buen
+26  A: 

There is a built in method for this:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

Result: 01-02-04-08-10-20

If you want it without the dashes, just remove them:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

Result: 010204081020

If you want a more compact representation, you can use Base64:

string base64 = Convert.ToBase64String(data);

Result: AQIECBAg

Guffa
how to convert back from Base64? i.e. the inverse of string base64 = Convert.ToBase64String(data);
ala
nevermind, i think i found it Convert.FromBase64String(..)
ala
A: 

You combine LINQ with string methods:

string hex = string.Join("",
  bin.Select(
    bin => bin.ToString("X2")
      ).ToArray());
mloskot
I like this answer as well.
acidzombie24
A: 

I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:

public static string ToHex(this byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx) 
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }

    return new string(c);
}

public static byte[] HexToBytes(this string str)
{
    if (str.Length == 0 || str.Length % 2 != 0)
        return new byte[0];

    byte[] buffer = new byte[str.Length / 2];
    char c;
    for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
    {
        // Convert first half of byte
        c = str[sx];
        buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

        // Convert second half of byte
        c = str[++sx];
        buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
    }

    return buffer;
}
Kurt
+1  A: 

Nice way to do this with LINQ...

var data = new byte[] { 1, 2, 4, 8, 16, 32 }; 
var hexString = data.Aggregate(new StringBuilder(), 
                               (sb,v)=>sb.Append("X2")
                              ).ToString();
Matthew Whited