1 16 17 package org.apache.commons.codec.binary; 18 19 import org.apache.commons.codec.BinaryDecoder; 20 import org.apache.commons.codec.BinaryEncoder; 21 import org.apache.commons.codec.DecoderException; 22 import org.apache.commons.codec.EncoderException; 23 24 31 public class Hex implements BinaryEncoder, BinaryDecoder { 32 33 36 private static final char[] DIGITS = { 37 '0', '1', '2', '3', '4', '5', '6', '7', 38 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 39 }; 40 41 54 public static byte[] decodeHex(char[] data) throws DecoderException { 55 56 int len = data.length; 57 58 if ((len & 0x01) != 0) { 59 throw new DecoderException("Odd number of characters."); 60 } 61 62 byte[] out = new byte[len >> 1]; 63 64 for (int i = 0, j = 0; j < len; i++) { 66 int f = toDigit(data[j], j) << 4; 67 j++; 68 f = f | toDigit(data[j], j); 69 j++; 70 out[i] = (byte) (f & 0xFF); 71 } 72 73 return out; 74 } 75 76 84 protected static int toDigit(char ch, int index) throws DecoderException { 85 int digit = Character.digit(ch, 16); 86 if (digit == -1) { 87 throw new DecoderException("Illegal hexadecimal charcter " + ch + " at index " + index); 88 } 89 return digit; 90 } 91 92 101 public static char[] encodeHex(byte[] data) { 102 103 int l = data.length; 104 105 char[] out = new char[l << 1]; 106 107 for (int i = 0, j = 0; i < l; i++) { 109 out[j++] = DIGITS[(0xF0 & data[i]) >>> 4 ]; 110 out[j++] = DIGITS[ 0x0F & data[i] ]; 111 } 112 113 return out; 114 } 115 116 130 public byte[] decode(byte[] array) throws DecoderException { 131 return decodeHex(new String (array).toCharArray()); 132 } 133 134 148 public Object decode(Object object) throws DecoderException { 149 try { 150 char[] charArray = object instanceof String ? ((String ) object).toCharArray() : (char[]) object; 151 return decodeHex(charArray); 152 } catch (ClassCastException e) { 153 throw new DecoderException(e.getMessage()); 154 } 155 } 156 157 167 public byte[] encode(byte[] array) { 168 return new String (encodeHex(array)).getBytes(); 169 } 170 171 182 public Object encode(Object object) throws EncoderException { 183 try { 184 byte[] byteArray = object instanceof String ? ((String ) object).getBytes() : (byte[]) object; 185 return encodeHex(byteArray); 186 } catch (ClassCastException e) { 187 throw new EncoderException(e.getMessage()); 188 } 189 } 190 191 } 192 193 | Popular Tags |