Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.function.IntUnaryOperator;
- public class FasterHex {
- private FasterHex() {}
- private static final short[] DECODE_TABLE = new short[13_159]; // ('f' << 7) + 'f' + 1
- static {
- Arrays.fill(DECODE_TABLE, (byte) -1);
- insertAll('0', '9');
- insertAll('A', 'F');
- insertAll('a', 'f');
- }
- private static void insertAll(int start, int end) {
- for (int i = start; i <= end; i++) {
- for (int j = '0'; j <= '9'; j++) insert(i, j);
- for (int j = 'A'; j <= 'F'; j++) insert(i, j);
- for (int j = 'a'; j <= 'f'; j++) insert(i, j);
- }
- }
- private static void insert(int i, int j) {
- // ASCII values are at most 7 bits
- DECODE_TABLE[i << 7 | j] = (short) (decodeNibble(i) << 4 | decodeNibble(j));
- }
- private static int decodeNibble(int c) {
- switch (c) {
- case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return c - '0';
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return c - ('A' - 0xA);
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return c - ('a' - 0xa);
- default: throw new AssertionError();
- }
- }
- public static byte[] decode(int offset, int len, IntUnaryOperator extractor) {
- byte[] dest = new byte[len / 2];
- for (int i = 0; i < dest.length; i++, offset += 2) {
- dest[i] = (byte) decodeByte(extractor, offset);
- }
- return dest;
- }
- private static short decodeByte(IntUnaryOperator extractor, int offset) {
- try {
- short val = DECODE_TABLE[extractor.applyAsInt(offset) << 7 | extractor.applyAsInt(offset+1)];
- if(val >= 0) {
- return val;
- }
- } catch (ArrayIndexOutOfBoundsException ignored) {
- /* fall through */
- }
- throw new IllegalArgumentException("invalid hex pair @ " + offset);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment