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