View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package org.waarp.common.utility;
21  
22  /**
23   *
24   */
25  public final class Hexa {
26    /**
27     * HEX_CHARS
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      // split each byte into 4 bit numbers and map to hex characters
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  }