byte[] to hex string

user34537 picture user34537 · Mar 8, 2009 · Viewed 530.9k times · Source

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?

Answer

Guffa picture Guffa · Mar 8, 2009

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