How do you convert a byte array to a hexadecimal string, and vice versa?

alextansc

How can you convert a byte array to a hexadecimal string, and vice versa?

Tomalak

Either:

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

or:

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

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert byte array to string and vice versa?

How to convert a float into a byte array and vice versa?

How to convert double byte character/string to single byte and vice versa?

How to convert numpy array to string and vice versa

Cannot convert String to byte array and vice versa in Java

Convert a byte array to integer in Java and vice versa

Convert file to byte array and vice versa

Converting String to Byte Array and vice versa

byte to string and vice versa

How to convert string into numpy array for tensorflow and vice versa

Convert a binary string to Hexadecimal and vice-versa in Elixir

How to convert String[] to String and vice versa in Android

How to convert a netty ByteBuf to a String and vice versa

how to convert joda datetime to String and vice versa

How to convert a string to hex and vice versa in c?

How can I convert double-float to byte array and vice versa in common lisp?

How to convert video/audio file to byte array and vice versa in android.?

BitmapImage to byte array and vice versa

Convert the string containing array and dict into the list and vice versa in c#

Convert ListView to Line separated String Array and vice versa

How do you convert a hexadecimal of type string to number in JS?

I want to convert a hexadecimal byte array to hexadecimal in string format

How to convert byte to hexadecimal string in Java

How to convert string variable to int and vice versa in CLASSIC ASP

How to convert WCHAR* to string in C++ and vice versa?

How many ways to convert bitmap to string and vice-versa?

Put byte array to JSON and vice versa

How to convert 16bit hexadecimal and binary representations to decimal float (and vice versa) in python?

What is the most efficient way to convert array of int to array of byte and vice versa?