public String ByteArrayToHexString(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-", ""); }
Faster way:
public String ByteArrayToHexString(byte[] bytes) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(bytes.Length * 2, bytes.Length * 2); foreach (byte b in bytes) { stringBuilder.AppendFormat("{0:x2}", b); } return stringBuilder.ToString(); }
And even faster:
public String ByteArrayToHexString(byte[] bytes) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(bytes.Length * 2); char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; foreach (byte b in bytes) { stringBuilder.Append(chars[b >> 4]).Append(chars[b & 0x0F]); } return stringBuilder.ToString(); }
And the faster is:
public String ByteArrayToHexString(byte[] bytes) { int length = bytes.Length; char[] chars = new char[length << 1]; for (int i = 0, j = 0; i < length; i++, j++ ) { byte b = (byte)(bytes[i] >> 4); chars[j] = (char)(b > 9 ? b + 0x37 : b + 0x30); j++; b = (byte)(bytes[i] & 0x0F); chars[j] = (char)(b > 9 ? b + 0x37 : b + 0x30); } return new String(chars); }
No comments:
Post a Comment