/// <summary> /// Returns a byte array as a formatted hex dump. /// </summary> /// <param name="data">The buffer to be dumped.</param> /// <param name="bytesPerLine">The number of bytes to dump per output line.</param> /// <param name="options">The formatting options.</param> /// <returns>The hex dump string.</returns> public static string HexDump(byte[] data, int bytesPerLine, HexDumpOption options) { return(HexDump(data, 0, data.Length, bytesPerLine, options)); }
/// <summary> /// Returns a byte array as a formatted hex dump. /// </summary> /// <param name="data">The buffer to be dumped.</param> /// <param name="start">The first byte to be dumped.</param> /// <param name="count">The number of bytes to be dumped.</param> /// <param name="bytesPerLine">The number of bytes to dump per output line.</param> /// <param name="options">The formatting options.</param> /// <returns>The hex dump string.</returns> public static string HexDump(byte[] data, int start, int count, int bytesPerLine, HexDumpOption options) { var sb = new StringBuilder(); int offset; int pos; if (count == 0) { return(string.Empty); } if (bytesPerLine <= 0) { throw new ArgumentException("bytesPerLine must be > 0", "bytesPerLine"); } offset = 0; if ((options & HexDumpOption.ShowOffsets) != 0) { if (count <= 0x0000FFFF) { sb.Append(offset.ToString("X4") + ": "); } else { sb.Append(offset.ToString("X8") + ": "); } } for (pos = start; pos < start + count;) { sb.Append(data[pos].ToString("X2") + " "); pos++; offset++; if (offset % bytesPerLine == 0) { if (offset != 0) { if ((options & HexDumpOption.ShowAnsi) != 0) { sb.Append("- "); for (int i = pos - bytesPerLine; i < pos; i++) { byte v = data[i]; if (v < 32 || v == 0x7F) { v = (byte)'.'; } sb.Append(Encoding.ASCII.GetString(new byte[] { v }, 0, 1)); } } sb.Append("\r\n"); } if ((options & HexDumpOption.ShowOffsets) != 0 && pos < start + count - 1) { if (count <= 0x0000FFFF) { sb.Append(offset.ToString("X4") + ": "); } else { sb.Append(offset.ToString("X8") + ": "); } } } } if ((options & HexDumpOption.ShowAnsi) != 0) { // Handle a final partial line int linePos = offset % bytesPerLine; if (linePos != 0) { for (int i = 0; i < bytesPerLine - linePos; i++) { sb.Append(" "); } sb.Append("- "); for (int i = pos - linePos; i < pos; i++) { byte v = data[i]; if (v < 32 || v == 0x7F) { v = (byte)'.'; } sb.Append(Encoding.ASCII.GetString(new byte[] { v }, 0, 1)); } sb.Append("\r\n"); } } return(sb.ToString()); }