Home >Backend Development >C++ >How Can I Efficiently Convert Hex Strings to Byte Arrays in C#?

How Can I Efficiently Convert Hex Strings to Byte Arrays in C#?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 13:01:091047browse

How Can I Efficiently Convert Hex Strings to Byte Arrays in C#?

C# Hex String to Byte Array Conversion: A Concise Approach

Directly converting hex strings to byte arrays isn't natively supported in C#. However, a clean and efficient solution leveraging LINQ is readily available.

A Streamlined LINQ Solution

This elegant LINQ-based method elegantly handles the conversion:

<code class="language-csharp">public static byte[] HexStringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}</code>

This code iterates through the hex string, selecting pairs of characters (representing hexadecimal digits). Convert.ToByte efficiently transforms each pair into its byte equivalent, and the result is compiled into a byte array. The use of LINQ makes the code concise and readable.

The above is the detailed content of How Can I Efficiently Convert Hex Strings to Byte Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn