1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io;
18
19 import java.io.IOException;
20 import java.io.OutputStream;
21
22
23
24
25
26
27
28
29
30
31
32
33
34 public class HexDump {
35
36
37
38
39 public HexDump() {
40 super();
41 }
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 public static void dump(byte[] data, long offset,
60 OutputStream stream, int index)
61 throws IOException, ArrayIndexOutOfBoundsException,
62 IllegalArgumentException {
63
64 if ((index < 0) || (index >= data.length)) {
65 throw new ArrayIndexOutOfBoundsException(
66 "illegal index: " + index + " into array of length "
67 + data.length);
68 }
69 if (stream == null) {
70 throw new IllegalArgumentException("cannot write to nullstream");
71 }
72 long display_offset = offset + index;
73 StringBuffer buffer = new StringBuffer(74);
74
75 for (int j = index; j < data.length; j += 16) {
76 int chars_read = data.length - j;
77
78 if (chars_read > 16) {
79 chars_read = 16;
80 }
81 buffer.append(dump(display_offset)).append(' ');
82 for (int k = 0; k < 16; k++) {
83 if (k < chars_read) {
84 buffer.append(dump(data[k + j]));
85 } else {
86 buffer.append(" ");
87 }
88 buffer.append(' ');
89 }
90 for (int k = 0; k < chars_read; k++) {
91 if ((data[k + j] >= ' ') && (data[k + j] < 127)) {
92 buffer.append((char) data[k + j]);
93 } else {
94 buffer.append('.');
95 }
96 }
97 buffer.append(EOL);
98 stream.write(buffer.toString().getBytes());
99 stream.flush();
100 buffer.setLength(0);
101 display_offset += chars_read;
102 }
103 }
104
105
106
107
108 public static final String EOL =
109 System.getProperty("line.separator");
110 private static final StringBuffer _lbuffer = new StringBuffer(8);
111 private static final StringBuffer _cbuffer = new StringBuffer(2);
112 private static final char[] _hexcodes =
113 {
114 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
115 'A', 'B', 'C', 'D', 'E', 'F'
116 };
117 private static final int[] _shifts =
118 {
119 28, 24, 20, 16, 12, 8, 4, 0
120 };
121
122
123
124
125
126
127
128 private static StringBuffer dump(long value) {
129 _lbuffer.setLength(0);
130 for (int j = 0; j < 8; j++) {
131 _lbuffer
132 .append(_hexcodes[((int) (value >> _shifts[j])) & 15]);
133 }
134 return _lbuffer;
135 }
136
137
138
139
140
141
142
143 private static StringBuffer dump(byte value) {
144 _cbuffer.setLength(0);
145 for (int j = 0; j < 2; j++) {
146 _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]);
147 }
148 return _cbuffer;
149 }
150
151 }