1 | class utilTest {
|
---|
2 |
|
---|
3 | public static void main(String[] argv) throws Throwable {
|
---|
4 | byte[] b = new byte[] {
|
---|
5 | 0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab,
|
---|
6 | (byte) 0xcd, (byte) 0xef
|
---|
7 | };
|
---|
8 | String s = "0123456789ABCDEF";
|
---|
9 | System.out.println(toString(b));
|
---|
10 | System.out.println(s);
|
---|
11 | System.out.println(toString(toBytesFromString(s)));
|
---|
12 | }
|
---|
13 |
|
---|
14 | // The following comes from the GNU Crypto project gnu.crypto.util.Util
|
---|
15 |
|
---|
16 | private static final char[] HEX_DIGITS = {
|
---|
17 | '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
|
---|
18 | };
|
---|
19 |
|
---|
20 | public static byte[] toBytesFromString(String s) {
|
---|
21 | int limit = s.length();
|
---|
22 | byte[] result = new byte[((limit + 1) / 2)];
|
---|
23 | int i = 0, j = 0;
|
---|
24 | if ((limit % 2) == 1) {
|
---|
25 | result[j++] = (byte) fromDigit(s.charAt(i++));
|
---|
26 | }
|
---|
27 | while (i < limit) {
|
---|
28 | result[j++] =
|
---|
29 | (byte)((fromDigit(s.charAt(i++)) << 4) | fromDigit(s.charAt(i++)));
|
---|
30 | }
|
---|
31 | return result;
|
---|
32 | }
|
---|
33 |
|
---|
34 | public static int fromDigit(char c) {
|
---|
35 | if (c >= '0' && c <= '9') {
|
---|
36 | return c - '0';
|
---|
37 | } else if (c >= 'A' && c <= 'F') {
|
---|
38 | return c - 'A' + 10;
|
---|
39 | } else if (c >= 'a' && c <= 'f') {
|
---|
40 | return c - 'a' + 10;
|
---|
41 | } else
|
---|
42 | throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
|
---|
43 | }
|
---|
44 |
|
---|
45 | public static String toString(byte[] ba) {
|
---|
46 | return toString(ba, 0, ba.length);
|
---|
47 | }
|
---|
48 |
|
---|
49 | public static final String toString(byte[] ba, int offset, int length) {
|
---|
50 | char[] buf = new char[length * 2];
|
---|
51 | for (int i = 0, j = 0, k; i < length; ) {
|
---|
52 | k = ba[offset + i++];
|
---|
53 | buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
|
---|
54 | buf[j++] = HEX_DIGITS[ k & 0x0F];
|
---|
55 | }
|
---|
56 | return new String(buf);
|
---|
57 | }
|
---|
58 | }
|
---|