blob: ffceded186634e033de373e5a39dfd3a7c19eeb3 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.hex;
2
3import java.io.*;
4
Stuart McCullochbb014372012-06-07 21:57:32 +00005/*
6 * Hex converter.
7 *
8 * TODO Implement string to byte[]
9 */
10public class Hex {
Stuart McCulloch2286f232012-06-15 13:27:53 +000011 final static char[] HEX = {
12 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
13 };
14
Stuart McCullochbb014372012-06-07 21:57:32 +000015 public final static byte[] toByteArray(String string) {
16 string = string.trim();
Stuart McCulloch2286f232012-06-15 13:27:53 +000017 if ((string.length() & 1) != 0)
Stuart McCullochbb014372012-06-07 21:57:32 +000018 throw new IllegalArgumentException("a hex string must have an even length");
19
Stuart McCulloch2286f232012-06-15 13:27:53 +000020 byte[] out = new byte[string.length() / 2];
21 for (int i = 0; i < out.length; i++) {
22 int high = nibble(string.charAt(i * 2)) << 4;
23 int low = nibble(string.charAt(i * 2 + 1));
Stuart McCullochbb014372012-06-07 21:57:32 +000024 out[i] = (byte) (high + low);
25 }
26 return out;
27 }
28
Stuart McCulloch2286f232012-06-15 13:27:53 +000029 public final static int nibble(char c) {
Stuart McCullochbb014372012-06-07 21:57:32 +000030 if (c >= '0' && c <= '9')
31 return c - '0';
Stuart McCulloch2286f232012-06-15 13:27:53 +000032
33 if (c >= 'A' && c <= 'F')
Stuart McCullochbb014372012-06-07 21:57:32 +000034 return c - 'A' + 10;
Stuart McCulloch2286f232012-06-15 13:27:53 +000035 if (c >= 'a' && c <= 'f')
Stuart McCullochbb014372012-06-07 21:57:32 +000036 return c - 'a' + 10;
Stuart McCulloch2286f232012-06-15 13:27:53 +000037
Stuart McCullochbb014372012-06-07 21:57:32 +000038 throw new IllegalArgumentException("Not a hex digit: " + c);
39 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000040
Stuart McCullochbb014372012-06-07 21:57:32 +000041 public final static String toHexString(byte data[]) {
42 StringBuilder sb = new StringBuilder();
43 try {
Stuart McCulloch2286f232012-06-15 13:27:53 +000044 append(sb, data);
45 }
46 catch (IOException e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000047 // cannot happen with sb
48 }
49 return sb.toString();
50 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000051
52 public final static void append(Appendable sb, byte[] data) throws IOException {
53 for (int i = 0; i < data.length; i++) {
54 sb.append(nibble(data[i] >> 4));
55 sb.append(nibble(data[i]));
Stuart McCullochbb014372012-06-07 21:57:32 +000056 }
57 }
58
Stuart McCulloch2286f232012-06-15 13:27:53 +000059 private final static char nibble(int i) {
Stuart McCullochbb014372012-06-07 21:57:32 +000060 return HEX[i & 0xF];
61 }
62}