1 package com.protomatter.util; 2 3 52 53 import java.io.*; 54 import java.text.*; 55 56 60 public class ByteDisplay 61 { 62 private static String ZERO = "0"; 64 private static String DOT = "."; 65 private static String SPACE = " "; 66 private static String TWO_SPACE = " "; 67 private static String THREE_SPACE = " "; 68 private static String CR = "\n"; 69 private static String HEADER 70 = "offset hex data ascii data\n"; 71 72 75 public static String displayBytes(int b) 76 { 77 byte[] thebyte = new byte[1]; 78 thebyte[0] = (byte)b; 79 return displayBytes(thebyte); 80 } 81 82 85 public static String displayBytes(byte[] b) 86 { 87 return displayBytes(b, 0, b.length); 88 } 89 90 94 public static String displayBytes(byte[] b, int off, int len) 95 { 96 StringBuffer buf = new StringBuffer (2048); 97 int end = off + len; 98 buf.append(HEADER); 99 int i, j, c; 100 101 for (i=off; i<end; i+=16) 102 { 103 if (i<100000) buf.append(SPACE); 104 if (i<10000) buf.append(SPACE); 105 if (i<1000) buf.append(SPACE); 106 if (i<100) buf.append(SPACE); 107 if (i<10) buf.append(SPACE); 108 buf.append(String.valueOf(i)); 109 buf.append(THREE_SPACE); 110 111 for (j=i; j<end && j<i+16; j++) 113 { 114 c = b[j] & 0xff; 115 if (c < 16) buf.append(ZERO); 116 buf.append(Integer.toHexString(c)); 117 buf.append(SPACE); 118 } 119 if (j == end) { 121 while (j++<i+16) 122 buf.append(THREE_SPACE); 123 } 124 125 buf.append(TWO_SPACE); 127 for (j=i; j<end && j<i+16; j++) 128 { 129 c = b[j] & 0xff; 130 if (c < 32 || c > 127) 131 buf.append(DOT); 132 else 133 buf.append((char)c); 134 } 135 buf.append(CR); 136 } 137 return buf.toString(); 138 } 139 140 144 public static void main(String args[]) 145 { 146 if (args.length != 1 && args.length != 2) 147 { 148 System.out.println("Usage: ByteDisplay filename [size]"); 149 System.exit(0); 150 } 151 try 152 { 153 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 154 FileInputStream in = new FileInputStream(new File(args[0])); 155 int size = Integer.MAX_VALUE; 156 if (args.length == 2) 157 size = Integer.parseInt(args[1]); 158 159 byte[] buffer = new byte[16]; 160 int read = 0; 161 int total = 0; 162 while ( ((read = in.read(buffer)) != -1) && (total < size)) 163 { 164 bytes.write(buffer, 0, read); 165 total += read; 166 } 167 System.out.println("Read " + bytes.size() + " bytes from " + args[0]); 168 System.out.println(displayBytes(bytes.toByteArray())); 169 } 170 catch (Exception x) 171 { 172 x.printStackTrace(); 173 } 174 } 175 } 176 | Popular Tags |