Dump a byte buffer as hex
6
More often than not, if your trying to work out what's going wrong with your subclass of InputStream, why the character encoding is getting lost in your database, or your file format reader is failing, you'll need to dump a byte buffer out in a useable form.
Here's two methods, one which appends to a StringBuffer, one which simply prints out to System.out
Tim.
(NB: The line: sb.append( "n" ) ; SHOULD have a leading slash ie: sb.append( "\n" ) ; but the formatter seems to remove it...
Here's two methods, one which appends to a StringBuffer, one which simply prints out to System.out
Tim.
(NB: The line: sb.append( "n" ) ; SHOULD have a leading slash ie: sb.append( "\n" ) ; but the formatter seems to remove it...
public static void dumpHex( StringBuffer sb, byte[] b )
{
for( int i = 0 ; i < b.length ; ++i )
{
if( i % 16 == 0 )
{
sb.append( Integer.toHexString( ( i & 0xFFFF ) | 0x10000 ).substring( 1, 5 ) + " - " ) ;
}
sb.append( Integer.toHexString( ( b[ i ] & 0xFF ) | 0x100 ).substring( 1, 3 ) + " " ) ;
if( i % 16 == 15 || i == b.length - 1 )
{
int j ;
for( j = 16 - i % 16 ; j > 1 ; --j )
sb.append( " " ) ;
sb.append( " - " ) ;
int start = ( i / 16 ) * 16 ;
int end = ( b.length < i + 1 ) ? b.length : ( i + 1 ) ;
for( j = start ; j < end ; ++j )
if( b[ j ] >= 32 && b[ j ] <= 126 )
sb.append( ( char )b[ j ] ) ;
else
sb.append( "." ) ;
sb.append( "\n" ) ;
}
}
}
public static void dumpHex( byte[] b )
{
StringBuffer sb = new StringBuffer() ;
dumpHex( sb, b ) ;
System.out.println( sb.toString() ) ;
}






=================
Matthew R. Miller
http://bluecreststudios.com
http://www.codeandcoffee.com