Formatting Byte Arrays in PowerShell

A few years ago, I posted a small utility class I kept around to dump byte arrays in a nice format for reading. I still use that a bit, but got tired of having to fool with test projects to use it sometimes during my debugging sessions, so I finally broke down and just ported it into a PowerShell function:

function byteToChar([byte]$b) {
   if ( $b -lt 32 -or $b  -gt 127 ) {
      '.'
   } else {
      [char]$b
   }
}
function format-bytes($bytes, $bytesPerLine = 8) {
   $buffer = new-object system.text.stringbuilder
   for ( $offset=0; $offset -lt $bytes.Length; $offset += $bytesPerLine ) {
      [void]$buffer.AppendFormat('{0:X8}   ', $offset)
      $numBytes = [math]::min($bytesPerLine, $bytes.Length - $offset)
      for ( $i=0; $i -lt $numBytes; $i++ ) {
         [void]$buffer.AppendFormat('{0:X2} ', $bytes[$offset+$i])
      }
      [void]$buffer.Append(' ' * ((($bytesPerLine - $numBytes)*3)+3))
      for ( $i=0; $i -lt $numBytes; $i++ ) {
         [void]$buffer.Append( (byteToChar $bytes[$offset + $i]) )
      }
      [void]$buffer.Append("`n")
   }
   $buffer.ToString()
}

It’s not fancy or fast, but it does the trick pretty nicely. I use PowerShell a lot during my debugging sessions, be that to quickly test things or make simple calculations, and this will be another useful tool in my PowerShell arsenal. It already proved quite useful today :-) . Here’s what the output looks like:

§ hyperion {~} format-bytes $bytes 16
00000000   60 30 06 09 2A 86 48 86 F7 12 01 02 02 02 01 11    `0..*.H.........
00000010   00 FF FF FF FF 63 9E C7 4F 19 35 B7 30 74 CD 5A    .....c..O.5.0t.Z
00000020   26 5E C0 ED CE 8A 3D 05 C8 28 9B 10 C0 01 00 2E    &^....=..(......
00000030   E0 01                                              ..

4 Comments

  1. Pingback: Arjan’s World » LINKBLOG for Sep 4, 2009

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>