01: // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
02:
03: package org.xbill.DNS.utils;
04:
05: import java.io.*;
06:
07: /**
08: * Routines for converting between Strings of hex-encoded data and arrays of
09: * binary data. This is not actually used by DNS.
10: *
11: * @author Brian Wellington
12: */
13:
14: public class base16 {
15:
16: private static final String Base16 = "0123456789ABCDEF";
17:
18: private base16() {
19: }
20:
21: /**
22: * Convert binary data to a hex-encoded String
23: * @param b An array containing binary data
24: * @return A String containing the encoded data
25: */
26: public static String toString(byte[] b) {
27: ByteArrayOutputStream os = new ByteArrayOutputStream();
28:
29: for (int i = 0; i < b.length; i++) {
30: short value = (short) (b[i] & 0xFF);
31: byte high = (byte) (value >> 4);
32: byte low = (byte) (value & 0xF);
33: os.write(Base16.charAt(high));
34: os.write(Base16.charAt(low));
35: }
36: return new String(os.toByteArray());
37: }
38:
39: /**
40: * Convert a hex-encoded String to binary data
41: * @param str A String containing the encoded data
42: * @return An array containing the binary data, or null if the string is invalid
43: */
44: public static byte[] fromString(String str) {
45: ByteArrayOutputStream bs = new ByteArrayOutputStream();
46: byte[] raw = str.getBytes();
47: for (int i = 0; i < raw.length; i++) {
48: if (!Character.isWhitespace((char) raw[i]))
49: bs.write(raw[i]);
50: }
51: byte[] in = bs.toByteArray();
52: if (in.length % 2 != 0) {
53: return null;
54: }
55:
56: bs.reset();
57: DataOutputStream ds = new DataOutputStream(bs);
58:
59: for (int i = 0; i < in.length; i += 2) {
60: byte high = (byte) Base16.indexOf(Character
61: .toUpperCase((char) in[i]));
62: byte low = (byte) Base16.indexOf(Character
63: .toUpperCase((char) in[i + 1]));
64: try {
65: ds.writeByte((high << 4) + low);
66: } catch (IOException e) {
67: }
68: }
69: return bs.toByteArray();
70: }
71:
72: }
|