View Javadoc

1   /*
2    *  Copyright 2006 Simon Raess
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.beep4j.internal.util;
17  
18  import java.io.OutputStream;
19  import java.io.OutputStreamWriter;
20  import java.io.PrintWriter;
21  import java.io.StringWriter;
22  import java.io.Writer;
23  import java.nio.ByteBuffer;
24  import java.nio.charset.Charset;
25  
26  public final class HexDump {
27  	
28  	public static final String dump(ByteBuffer buffer) {
29  		StringWriter writer = new StringWriter();
30  		dump(buffer, writer);
31  		return writer.getBuffer().toString();
32  	}
33  	
34  	public static final void dump(ByteBuffer buffer, OutputStream out) {
35  		Writer writer = new OutputStreamWriter(out, Charset.forName("US-ASCII"));
36  		dump(buffer, writer);
37  	}
38  	
39  	public static final void dump(ByteBuffer buffer, Writer w) {
40  		PrintWriter writer = new PrintWriter(w);
41  		buffer = buffer.asReadOnlyBuffer();
42  		
43  		int remaining = buffer.remaining();
44  		byte[] lineBuffer = new byte[16];
45  		
46  		for (int i = 0; i < remaining; i += 16) {
47  			int length = Math.min(16, buffer.remaining());
48  			buffer.get(lineBuffer, 0, length);
49  			
50  			for (int j = 0; j < length; j++) {
51  				String hex = Integer.toHexString(lineBuffer[j] & 0xFF);
52  				hex = hex.length() == 1 ? "0" + hex : hex;
53  				writer.write(hex + " ");
54  			}
55  			
56  			for (int j = length; j < 16; j++) {
57  				writer.write("   ");
58  			}
59  			
60  			writer.write("   ");
61  			
62  			for (int j = 0; j < length; j++) {
63  				writer.write(asChar(lineBuffer[j]) + " ");
64  			}
65  			
66  			writer.write("\r\n");
67  		}
68  		
69  		writer.flush();
70  	}
71  	
72  	private static final char asChar(byte b) {
73  		if (b > 0x20) {
74  			return (char) b;
75  		} else {
76  			return '.';
77  		}
78  	}
79  	
80  }