How to convert hex string to byte array in C#
By Tan Lee Published on Mar 04, 2025 170
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024