HOW DO YOU CONVERT BYTE ARRAY TO HEXADECIMAL STRING, AND VICE-VERSA?

john rob

Total Post:108

Points:756
Posted by  john rob
C# 
C#
 1037  View(s)
Ratings:
Rate this:
Hi Everyone!

This is probably a common question over the Internet, but I couldn't find an answer that neatly explains how you can convert a byte array to a hexadecimal string, and vice-versa.

Thanks in advance. 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How do you convert Byte Array to Hexadecimal String, and vice-versa?

    Hi John!

    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)
    {
      string hex = BitConverter.ToString(ba);
      return hex.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;
    }
    Edit: you can improve performance for long strings by using a single pass parser, like so:

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!