Search code examples
c#arrayshex

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


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


Solution

  • You can use Convert.ToHexString starting with .NET 5.
    There's also a method for the reverse operation: Convert.FromHexString.


    For older versions of .NET you can either use:

    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.