using System; namespace NFC.Helper { /// /// Converts to and from Byte Array from and to String /// public static class HexConverter { /// /// Converts byte[] to string with HEX Code /// No 0x is created /// /// Data public static string ConvertToHexString(byte[] data) { return BitConverter.ToString(data).Replace("-", "").ToLower(); } /// /// Converts string with HEX Code to byte[] /// No 0x is requiered /// /// Data public static byte[] ConvertFromHexString(string data) { if (data.Length % 2 == 1) throw new Exception("Data Length is uneven."); byte[] arr = new byte[data.Length >> 1]; for (int i = 0; i < data.Length >> 1; ++i) { arr[i] = (byte)((GetHexVal(data[i << 1]) << 4) + (GetHexVal(data[(i << 1) + 1]))); } return arr; } private static int GetHexVal(char hex) { int val = (int)hex; //For uppercase A-F letters: //return val - (val < 58 ? 48 : 55); //For lowercase a-f letters: //return val - (val < 58 ? 48 : 87); //Or the two combined, but a bit slower: return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); } } }