1 64 65 package com.jcorporate.expresso.core.misc; 66 67 import com.jcorporate.expresso.kernel.util.FastStringBuffer; 68 69 70 78 public class HexEncoder { 79 80 83 private static final char[] codes = { 84 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 85 'E', 'F' 86 }; 87 88 private static final String thisClass = HexEncoder.class.getName(); 89 90 public HexEncoder() { 91 } 92 93 100 private static int convertToNumber(char inChar) { 101 if (inChar >= '0' && inChar <= '9') { 102 return inChar - '0'; 103 } 104 if (inChar >= 'A' && inChar <= 'F') { 105 return inChar - 'A' + 10; 106 } 107 if (inChar >= 'a' && inChar <= 'f') { 108 return inChar - 'a' + 10; 109 } 110 111 return -1; 112 } 113 114 125 public static byte[] decode(String inputData) 126 throws IllegalArgumentException { 127 128 if (inputData == null) { 130 throw new IllegalArgumentException (thisClass + "decode(String)" + 131 " inputData must not be null"); 132 } 133 134 int len = inputData.length(); 135 136 if (len == 0) { 137 throw new IllegalArgumentException (thisClass + "decode(String)" + 138 " inputData must be of length > 0"); 139 } 140 if (len % 2 != 0) { 141 throw new IllegalArgumentException (thisClass + "decode(String)" + 142 " inputData must be of even length"); 143 } 144 145 byte[] finalResult = new byte[len / 2]; 147 int temp; 148 int arrayPos = 0; 149 150 for (int i = 0; i < len; i++) { 151 temp = HexEncoder.convertToNumber(inputData.charAt(i)); 152 153 if (temp < 0) { 154 throw new IllegalArgumentException (thisClass + "decode(String)" + 155 " illegal hex character in input Data: " + 156 inputData); 157 } 158 if (i % 2 == 1) { 159 byte temp2 = (byte) (finalResult[arrayPos] << 4); 160 finalResult[arrayPos] = (byte) (temp2 | (byte) temp); 161 arrayPos++; 162 } else { 163 finalResult[arrayPos] = (byte) temp; 164 } 165 } 166 167 return finalResult; 168 } 169 170 171 178 public static String encode(byte[] inputData) 179 throws IllegalArgumentException { 180 int len = inputData.length; 181 182 if (len == 0) { 183 throw new IllegalArgumentException (thisClass + ".encode(byte)" + 184 " inputData must be of length > 0"); 185 } 186 187 FastStringBuffer buffer = new FastStringBuffer(len * 2); 188 189 for (int i = 0; i < len; i++) { 190 int a = inputData[i]; 191 192 if (a < 0) { 193 a = (a & 0x00FF); } 195 196 a >>>= 4; 197 buffer.append(codes[a]); 198 buffer.append(codes[inputData[i] & 0x0F]); 199 } 200 201 return buffer.toString(); 202 } 203 204 205 212 public static String encode(String s) 213 throws IllegalArgumentException { 214 return encode(s.getBytes()); 215 } 216 217 218 } 219 220 | Popular Tags |