HexTranslator.java revision 2ad60cfc28e14ee8f0bb038720836a4696c478ad
1package org.bouncycastle.util.encoders; 2 3/** 4 * Converters for going from hex to binary and back. Note: this class assumes ASCII processing. 5 */ 6public class HexTranslator 7 implements Translator 8{ 9 private static final byte[] hexTable = 10 { 11 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', 12 (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' 13 }; 14 15 /** 16 * size of the output block on encoding produced by getDecodedBlockSize() 17 * bytes. 18 */ 19 public int getEncodedBlockSize() 20 { 21 return 2; 22 } 23 24 public int encode( 25 byte[] in, 26 int inOff, 27 int length, 28 byte[] out, 29 int outOff) 30 { 31 for (int i = 0, j = 0; i < length; i++, j += 2) 32 { 33 out[outOff + j] = hexTable[(in[inOff] >> 4) & 0x0f]; 34 out[outOff + j + 1] = hexTable[in[inOff] & 0x0f]; 35 36 inOff++; 37 } 38 39 return length * 2; 40 } 41 42 /** 43 * size of the output block on decoding produced by getEncodedBlockSize() 44 * bytes. 45 */ 46 public int getDecodedBlockSize() 47 { 48 return 1; 49 } 50 51 public int decode( 52 byte[] in, 53 int inOff, 54 int length, 55 byte[] out, 56 int outOff) 57 { 58 int halfLength = length / 2; 59 byte left, right; 60 for (int i = 0; i < halfLength; i++) 61 { 62 left = in[inOff + i * 2]; 63 right = in[inOff + i * 2 + 1]; 64 65 if (left < (byte)'a') 66 { 67 out[outOff] = (byte)((left - '0') << 4); 68 } 69 else 70 { 71 out[outOff] = (byte)((left - 'a' + 10) << 4); 72 } 73 if (right < (byte)'a') 74 { 75 out[outOff] += (byte)(right - '0'); 76 } 77 else 78 { 79 out[outOff] += (byte)(right - 'a' + 10); 80 } 81 82 outOff++; 83 } 84 85 return halfLength; 86 } 87} 88