1 22 package org.jboss.tm.recovery; 23 24 import java.io.*; 25 26 32 public class HexDump 33 { 34 40 public static String fromBuffer(byte[] buffer) 41 { 42 int n; 43 final int N = 16; 44 StringBuffer sb = new StringBuffer ("\n"); 45 46 for (int i = 0; (n = Math.min(N, buffer.length - i)) != 0; i = i + n) 47 { 48 sb.append(toHexString(i) + ": "); 49 for (int j = 0; j < n ; j++) 50 sb.append(toHexString(buffer[i + j]) + " "); 51 for (int j = n; j < N; j++) 52 sb.append(" "); 53 sb.append(" "); 54 for (int j = 0; j < n ; j++) 55 sb.append(toDisplayableChar(buffer[i + j])); 56 sb.append("\n"); 57 } 58 return sb.toString(); 59 } 60 61 67 private static String toHexString(byte b) 68 { 69 int i = b; if (i < 0) 71 i = i - (int) 0xffffff00; String hexStr = Integer.toHexString(i); 73 return (hexStr.length() < 2) ? "0" + hexStr : hexStr; 74 } 75 76 84 private static String toHexString(int n) 85 { 86 String hexStr = Integer.toHexString(n); 87 while (hexStr.length() < 8) 88 hexStr = " " + hexStr; 89 return hexStr; 90 } 91 92 98 private static char toDisplayableChar(byte b) 99 { 100 char c = (char) b; 101 if (c >= 0x20 && c < 0x7f) 102 return c; 103 else 104 return '.'; 105 } 106 107 110 public static void main(String [] args) throws IOException 111 { 112 InputStream in; 113 byte[] ibuf = new byte[4096]; 114 115 if (args.length > 1) 116 { 117 System.err.println("HexDump usage: java HexDump [file]"); 118 System.exit(1); 119 } 120 in = (args.length == 0) ? System.in : new FileInputStream(args[0]); 121 int n = in.read(ibuf); 122 while (n > 0) 123 { 124 byte[] buf = new byte[n]; 125 System.arraycopy(ibuf, 0, buf, 0, n); 126 System.out.print(fromBuffer(buf)); 127 n = in.read(ibuf); 128 } 129 if (args.length != 0) 130 in.close(); 131 } 132 133 } 134 | Popular Tags |