1 16 package org.apache.commons.io; 17 18 import java.io.IOException ; 19 import java.io.OutputStream ; 20 21 32 public class HexDump { 33 34 37 public HexDump() { } 38 39 55 56 public static void dump(byte[] data, long offset, 57 OutputStream stream, int index) 58 throws IOException , ArrayIndexOutOfBoundsException , 59 IllegalArgumentException { 60 if ((index < 0) || (index >= data.length)) { 61 throw new ArrayIndexOutOfBoundsException ( 62 "illegal index: " + index + " into array of length " 63 + data.length); 64 } 65 if (stream == null) { 66 throw new IllegalArgumentException ("cannot write to nullstream"); 67 } 68 long display_offset = offset + index; 69 StringBuffer buffer = new StringBuffer (74); 70 71 for (int j = index; j < data.length; j += 16) { 72 int chars_read = data.length - j; 73 74 if (chars_read > 16) { 75 chars_read = 16; 76 } 77 buffer.append(dump(display_offset)).append(' '); 78 for (int k = 0; k < 16; k++) { 79 if (k < chars_read) { 80 buffer.append(dump(data[k + j])); 81 } else { 82 buffer.append(" "); 83 } 84 buffer.append(' '); 85 } 86 for (int k = 0; k < chars_read; k++) { 87 if ((data[k + j] >= ' ') && (data[k + j] < 127)) { 88 buffer.append((char) data[k + j]); 89 } else { 90 buffer.append('.'); 91 } 92 } 93 buffer.append(EOL); 94 stream.write(buffer.toString().getBytes()); 95 stream.flush(); 96 buffer.setLength(0); 97 display_offset += chars_read; 98 } 99 } 100 101 102 public static final String EOL = 103 System.getProperty("line.separator"); 104 private static final StringBuffer _lbuffer = new StringBuffer (8); 105 private static final StringBuffer _cbuffer = new StringBuffer (2); 106 private static final char _hexcodes[] = 107 { 108 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 109 'E', 'F' 110 }; 111 private static final int _shifts[] = 112 { 113 28, 24, 20, 16, 12, 8, 4, 0 114 }; 115 116 private static StringBuffer dump(long value) { 117 _lbuffer.setLength(0); 118 for (int j = 0; j < 8; j++) { 119 _lbuffer 120 .append(_hexcodes[((int) (value >> _shifts[j])) & 15]); 121 } 122 return _lbuffer; 123 } 124 125 private static StringBuffer dump(byte value) { 126 _cbuffer.setLength(0); 127 for (int j = 0; j < 2; j++) { 128 _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]); 129 } 130 return _cbuffer; 131 } 132 } 133 | Popular Tags |