Home > Backend Development > C++ > How to Efficiently Convert a Hex String to a Byte Array in C#?

How to Efficiently Convert a Hex String to a Byte Array in C#?

Barbara Streisand
Release: 2025-02-01 12:46:09
Original
374 people have browsed it

How to Efficiently Convert a Hex String to a Byte Array in C#?

C#Sixteen -in -made string to the conversion of byte array

In C#, converting the hexadecimal string into byte array can be implemented to achieve the combination of linq (language integration query) and string operation.

The following is an example code:

This method accepts a hexadecimal string as input and executes the following steps:
<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>
Copy after login

It uses to generate the index sequence of characters in the string.
  1. It uses to screen the sequence, which only contains the characters that indexes the indexes to ensure that the byte is paired. Enumerable.Range(0, hex.Length)
  2. It uses to select each character for a sub -string, and use
  3. to convert it into bytes. Parameters 16 Specify the conversion from the hexadecimal number base. Where(x => x % 2 == 0)
  4. Use to convert the generated byte sequence to array, thereby generating the required byte array.
  5. hex.Substring(x, 2) Convert.ToByte(hex.Substring(x, 2), 16) This method uses the powerful function of Linq, and demonstrates a method for effective analysis in C#and converting the hexadecimal string into byte array.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template