C#: Convert an array of bytes to an hexadecimal string
Posted by Guirec in .net , C# , code , extension methods , helper class
public static class HexadecimalConverter { static readonly string[] fLookupTable; static HexadecimalConverter() { // Populates cache fLookupTable = new string[256]; for (int i = 0; i < fLookupTable.Length; i++) fLookupTable[i] = i.ToString("X2"); } // converts a byte array to an hexa string public static string ToHexString(byte[] bytes) { if (bytes == null || bytes.Length == 0) return ""; char[] lChars = new char[bytes.Length * 2]; for (int i = 0, j = -1; i < bytes.Length; i++) { string lHex = fLookupTable[bytes[i]]; lChars[++j] = lHex[0]; lChars[++j] = lHex[1]; } return new string(lChars); } // Extension Method public static string ToHexadecimalString(this byte[] bytes) { return HexadecimalConverter.ToHexString(bytes); } }
0 Responses to "C#: Convert an array of bytes to an hexadecimal string"
Leave a Reply