1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.waarp.common.utility;
21
22
23
24
25 public final class Hexa {
26
27
28
29 private static final char[] HEX_CHARS = {
30 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
31 'f',
32 };
33
34 private Hexa() {
35 }
36
37 public static byte asByte(char a, char b) {
38 if (a >= HEX_CHARS[10]) {
39 a -= HEX_CHARS[10] - 10;
40 } else {
41 a -= HEX_CHARS[0];
42 }
43 if (b >= HEX_CHARS[10]) {
44 b -= HEX_CHARS[10] - 10;
45 } else {
46 b -= HEX_CHARS[0];
47 }
48 return (byte) ((a << 4) + b);
49 }
50
51 public static byte[] fromHex(final char[] hex) {
52 final int size = hex.length / 2;
53 final byte[] bytes = new byte[size];
54 for (int i = 0, j = 0; i < size; ) {
55 bytes[i++] = asByte(hex[j++], hex[j++]);
56 }
57 return bytes;
58 }
59
60 public static byte[] fromHex(final String hex) {
61 final char[] chars = hex.toCharArray();
62 final int size = chars.length / 2;
63 final byte[] bytes = new byte[size];
64 for (int i = 0, j = 0; i < size; ) {
65 bytes[i++] = asByte(chars[j++], chars[j++]);
66 }
67 return bytes;
68 }
69
70 public static char getHighHex(final byte value) {
71 return HEX_CHARS[(value & 0xF0) >> 4];
72 }
73
74 public static char getLowHex(final byte value) {
75 return HEX_CHARS[value & 0x0F];
76 }
77
78 public static String toHex(final byte[] bytes) {
79 final int size = bytes.length;
80 final int b16size = size * 2;
81 final char[] id = new char[b16size];
82
83
84 for (int i = 0, j = 0; i < size; i++) {
85 id[j++] = HEX_CHARS[(bytes[i] & 0xF0) >> 4];
86 id[j++] = HEX_CHARS[bytes[i] & 0x0F];
87 }
88 return new String(id);
89 }
90 }