November 20, 2004

Hex representations for byte arrays and ints

"4A 4F 55 4E 49 20 48 45 49 4B 4E 49 45 4D 49"? Today, among other things, I wrote a C# method that converts byte arrays to their hex representations. That's very simple actually - ToString does most of the grunt work, but some parameterizations help in customizing things.

public static string ToHexString(
  byte[] bytes, bool spacesBetweenBytes, bool upperCase) {

  StringBuilder sb = 
    new StringBuilder(bytes.Length*(spacesBetweenBytes ? 3 : 2));
  string byteFormat = 
    "{0:" + (upperCase ? 'X' : 'x') + "2}" + (spacesBetweenBytes ? " " : "");

  foreach (Byte b in bytes)
    sb.AppendFormat(byteFormat, b);

  // Cut off the last space if we were using spacesBetweenBytes
  if (spacesBetweenBytes && bytes.Length > 0)
    sb.Length--;

  return sb.ToString();
}

If the bytes parameter is an array of bytes 123 and 234, the hex representations by the combinations of the two boolean params are as follows:

ToHexString
w/ {123, 234}
spacesBetweenBytes
false
spacesBetweenBytes
true
upperCase false 7bea 7b ea
upperCase true 7BEA 7B EA

I believe you have no trouble guessing what this overload does:

public static string ToHexString(int num, bool spacesBetweenBytes, bool upperCase) {

  return ToHexString(
    BitConverter.GetBytes(num), 
    spacesBetweenBytes, 
    upperCase
  );
}

Update 2004-11-21 9:00 UTC+2: I made the int version use BitConverter instead of implicitly setting the byte order (endianness). Sorry about the edit; I must've been asleep when writing the entry.

Posted by Jouni Heikniemi at November 20, 2004 08:47 PM
.net
Comments
Post a comment









Remember personal info?