Go Back

Converting Array of bytes to hex string

I was working on saving a byte array to an xml file and kept running into an error trying to deserialize it. The byte array was an a SHA512 hash so it was quite large and had characters that weren't valid xml in them.

Honestly, i can't remember what they were but the point is that I whipped together some code that would convert a byte array into a string of hexidecimal. I'm sure there's something not 'mathematically' correct about how it looks but it's basically converting

new byte[]{255,0,15} into "FF000F" and back the other way. I found it useful.

 

  public class NumberTranslations

    {

        public static byte[] HexToByte(string hex)

        {

            var bytes = new List<byte>();

            var hexes = new List<string>();

            char[] chars = hex.ToCharArray();

            for (int x = 0; x < chars.Length; x += 2)

            {

                hexes.Add(string.Concat(chars[x], chars[x + 1]));

            }

            foreach (string hexy in hexes)

            {

                bytes.Add(byte.Parse(hexy, NumberStyles.HexNumber));

            }

            return bytes.ToArray();

        }

 

        public static string ByteToHex(byte[] bytes)

        {

            var builder = new StringBuilder();

            foreach (byte number in bytes)

            {

                builder.Append(number.ToString("X").PadLeft(2, '0'));

            }

            return builder.ToString();

        }

    }

Facebook DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Furl it!

Post a comment!
  1. Formatting options