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