1 24 package fr.dyade.aaa.util; 25 26 29 public class Ubyte { 30 33 public static int unsignedValue(byte b) { 34 return (b >= 0 ? (int) b : 0x100 + b); 35 } 36 37 40 public static byte signedValue(int b) { 41 return (b <= Byte.MAX_VALUE ? (byte) b : (byte) (b - 0x100)); 42 } 43 44 47 public static String toHexString(byte b) { 48 String str = Integer.toHexString(unsignedValue(b)); 49 switch (str.length()) { 50 case 2: 51 return str; 52 case 1: 53 return "0" + str; 54 default: 55 throw new IllegalArgumentException ("error in Ubyte.toHexString(" + b + ")"); 57 } 58 } 59 60 72 static final char hexaDigits[] = { 73 '0', '1', '2', '3', '4', '5', '6', '7', 74 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 75 }; 76 public static String toHexString( 77 byte[] buffer, int start, int stop, 78 int bytesInBlock, String blockHeader, 79 int blocksInLine, String lineHeader, 80 int current) { 81 82 StringBuffer output = new StringBuffer (); 83 84 if (bytesInBlock == 0) bytesInBlock = Integer.MAX_VALUE; 85 if (blocksInLine == 0) blocksInLine = Integer.MAX_VALUE; 86 87 int k = bytesInBlock - (current % bytesInBlock); 89 int j = blocksInLine - ((current / bytesInBlock) % blocksInLine); 91 92 String header; 94 if (k != bytesInBlock) { 95 header = ""; 96 } else if (j != blocksInLine) { 97 header = blockHeader; 98 } else { 99 header = lineHeader; 100 } 101 102 int i = start; 103 printLoop: 104 while (true) { 105 while (j-- > 0) { 106 output.append(header); 107 while (k-- > 0) { 108 int value = unsignedValue(buffer[i]); 110 output.append(hexaDigits[value / 0x10]); 111 output.append(hexaDigits[value % 0x10]); 112 if (++i == stop) 114 break printLoop; 115 } 116 k = bytesInBlock; 117 header = blockHeader; 118 } 119 output.append('\n'); 120 j = blocksInLine; 121 header = lineHeader; 122 } 123 124 return output.toString(); 125 } 126 127 134 public static String toHexString(byte[] buffer, int start, int stop) { 135 return toHexString(buffer, start, stop, 2, " ", 8, "\t", 0); 136 } 137 } 138 | Popular Tags |