Home > Backend Development > C++ > How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?

How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?

Susan Sarandon
Release: 2025-02-03 08:09:38
Original
234 people have browsed it

How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?

Efficiently Converting Byte Arrays and Hexadecimal Strings

Many applications require converting byte arrays to hexadecimal strings and vice versa. This article explores efficient methods for this conversion in .NET.

Byte Array to Hexadecimal String

.NET 5 and later offer the simplest solution using Convert.ToHexString:

byte[] byteArray = { 1, 2, 3 };
string hexString = Convert.ToHexString(byteArray); 
Copy after login

For older .NET frameworks, two alternatives provide similar functionality:

Method 1 (Using StringBuilder):

public static string ByteArrayToHex(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}
Copy after login

Method 2 (Using BitConverter):

public static string ByteArrayToHex(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-", "");
}
Copy after login

Hexadecimal String to Byte Array

Converting a hexadecimal string back to a byte array can be achieved with this method:

public static byte[] HexToByteArray(string hex)
{
  int len = hex.Length;
  byte[] arr = new byte[len / 2];
  for (int i = 0; i < len; i += 2)
  {
    arr[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  }
  return arr;
}
Copy after login

For enhanced performance, utilizing Substring with Convert.ToByte directly avoids unnecessary intermediate conversions. This approach is particularly beneficial when dealing with large byte arrays.

The above is the detailed content of How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?. For more information, please follow other related articles on the PHP Chinese website!

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