In C#, what is the tidiest way to convert an array of bytes into a string of hex numbers?
Asked
Active
Viewed 2,412 times
2
-
duplicate http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c – Amirshk Jan 28 '10 at 02:58
-
You are right Am, missed that one – Craig Schwarze Jan 28 '10 at 03:05
3 Answers
2
BitConverter.ToString http://msdn.microsoft.com/en-us/library/system.bitconverter.tostring.aspx
You'll get hyphens between bytes in the string, but they are easily removed.

Eric Mickelsen
- 10,309
- 2
- 30
- 41
2
This should work... BitConverter is better, but this gives you more control (no hyphens) and you can get fancy with lambdas if you so wished :)
public string byteToHex(byte[] byteArray) {
StringBuilder result = new StringBuilder();
foreach (byte b in byteArray) {
result.AppendString(b.ToString("X2"));
}
return result.ToString();
}

Vinko Vrsalovic
- 330,807
- 53
- 334
- 373
1
Here's an extension I use when I need lowercase hex. e.g. Facebook requires lowercase for signing POST data.
private static string ToLowerCaseHexString(this IEnumerable<byte> hash)
{
return hash
.Select(b => String.Format("{0:x2}",
b))
.Aggregate((a, b) => a + b);
}
Might be quicker using a StringBuilder over linq .Aggregate, but the byte arrays I pass are short.

spender
- 117,338
- 33
- 229
- 351