January 18, 2009

Useful Byte Array Debugging Classes

Some useful debugging classes for debugging byte arrays. Useful for unit tests.
internal static class ByteArrayHelper
{
 // Output the byte array as a C# style byte array variable declaration 
 // where the variable name of the byte array is passed as a parameter
 public static string ToCSharpByteArrayDeclrn(string name, byte[] bytes)
 {
  StringBuilder res = new StringBuilder(bytes.Length*6 + 64 + name.Length);
  res.Append("byte[] " + name + " = new byte[" +
                      bytes.Length.ToString(CultureInfo.InvariantCulture) + "] { ");
  int ix = 0;
  for (; ix < bytes.Length - 1; ix++)
  {
   res.Append("0x" + bytes[ix].ToString("X2",
                                      CultureInfo.InvariantCulture) + ", ");
  }
  for (; ix < bytes.Length; ix++)
  {
   res.Append("0x" + bytes[ix].ToString("X2",
                                      CultureInfo.InvariantCulture));
  }
  res.Append(" };");
  return res.ToString();
 }

 // Checks whether 2 byte arrays are exactly the same, ie. they have 
 // the same length and the same values at each array entry
 public static bool AreTheSame(byte[] bytes1, byte[] bytes2)
 {
  bool areTheSame = (bytes1.Length == bytes2.Length);
  for (int ix = 0; (ix < bytes1.Length) && areTheSame; ix++)
  {
   areTheSame = bytes1[ix] == bytes2[ix];
  }
  return areTheSame;
 }
}

No comments: