How to convert hex string to byte array in C#
By FoxLearn 3/4/2025 9:57:19 AM 25
You can convert a hex string to a byte array in C# using a lookup table and bitwise operations for efficiency.
For example, Convert Hex String to Byte Array
using System; using System.Collections.Generic; public static class HexUtil { private static readonly Dictionary<char, byte> HexMap = new Dictionary<char, byte>() { { '0', 0x0 }, { '1', 0x1 }, { '2', 0x2 }, { '3', 0x3 }, { '4', 0x4 }, { '5', 0x5 }, { '6', 0x6 }, { '7', 0x7 }, { '8', 0x8 }, { '9', 0x9 }, { 'A', 0xA }, { 'B', 0xB }, { 'C', 0xC }, { 'D', 0xD }, { 'E', 0xE }, { 'F', 0xF }, { 'a', 0xA }, { 'b', 0xB }, { 'c', 0xC }, { 'd', 0xD }, { 'e', 0xE }, { 'f', 0xF } }; public static byte[] ToBytes(this string hex) { if (string.IsNullOrWhiteSpace(hex)) throw new ArgumentException("Hex string cannot be null or empty."); if (hex.Length % 2 != 0) throw new FormatException("Hex string must have an even number of characters."); bool hasPrefix = hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase); int startIndex = hasPrefix ? 2 : 0; byte[] bytes = new byte[(hex.Length - startIndex) / 2]; try { for (int i = startIndex, j = 0; i < hex.Length; i += 2, j++) { bytes[j] = (byte)((HexMap[hex[i]] << 4) | HexMap[hex[i + 1]]); } return bytes; } catch (KeyNotFoundException) { throw new FormatException("Hex string contains invalid characters."); } } }
Usage:
using System; class Program { static void Main() { string hexString = "0x4F2A"; byte[] byteArray = hexString.ToBytes(); Console.WriteLine(BitConverter.ToString(byteArray)); // Output: 4F-2A } }
In this example:
- Validation Checks: Ensures the string is not empty and has an even length.
- Handles
0x
Prefix: Skips0x
if present. - Lookup Table: Converts characters to their hexadecimal values.
- Bitwise Operations: Combines two half-bytes into a full byte.
This method is fast and efficient, suitable for performance-critical applications.
Categories
Popular Posts
Gentella Admin Template
11/14/2024
Material Dashboard Admin Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024
Regal Admin Dashboard Template
11/18/2024