Convert Byte Array to Hexidecimal String in C#
I had to write a function today which will take an arrayof bytes and convert those bytes into a hexidecimal string representation. This was part of an encryption algorithm. There are a couple on the net but they seem to be more complicated. Here is what I came up with (and this seems the simplest way to me, so there may be similar ones out there):
1 2 3 4 5 6 7 8 9 10 11 12 13 | public string ToHexString(byte[] array) { string vals = "0123456789ABCDEF"; StringBuilder result = new StringBuilder(); for (int i = 0; i < array.Length; i++) { result.Append(vals[array[i] >> 4]); result.Append(vals[array[i] & 15]); } return result.ToString(); } |
Follow Dave on Twitter
You coud do two other things:
1)
char [] chararray = new char[array.Length*2];
// Fill chararray with your vals
return new string(chararray);
2)
use the function to extend the byte[] array using C# 3.0 extension methods:
http://msdn.microsoft.com/en-us/library/bb383977.aspx