>>>>>> StringBuilder sb = new StringBuilder(length << 1); >>>>>>>
static string ToHex(byte[] bytes) > { > return "0X"+ BitConverter.ToString(bytes).Replace("-",string.Empty); > }That may even be faster ( but it instantiates a char[] )
// Converts an array of bytes into a String. public static String ToString (byte[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("byteArray"); } if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if (startIndex > value.Length - length) { throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall")); } Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (Int32.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i]= GetHexValue(b/16); chArray[i+1] = GetHexValue(b%16); chArray[i+2] = '-'; } // We don't need the last '-' character return new String(chArray, 0, chArray.Length - 1); } private static char GetHexValue(int i) { Contract.Assert( i >=0 && i <16, "i is out of range."); if (i<10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); }