Guest User

Faster hex decoder

a guest
Aug 5th, 2023
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | Source Code | 0 0
  1. import java.util.Arrays;
  2. import java.util.function.IntUnaryOperator;
  3.  
  4. public class FasterHex {
  5.  
  6.     private FasterHex() {}
  7.  
  8.     private static final short[] DECODE_TABLE = new short[13_159]; // ('f' << 7) + 'f' + 1
  9.  
  10.     static {
  11.         Arrays.fill(DECODE_TABLE, (byte) -1);
  12.         insertAll('0', '9');
  13.         insertAll('A', 'F');
  14.         insertAll('a', 'f');
  15.     }
  16.  
  17.     private static void insertAll(int start, int end) {
  18.         for (int i = start; i <= end; i++) {
  19.             for (int j = '0'; j <= '9'; j++) insert(i, j);
  20.             for (int j = 'A'; j <= 'F'; j++) insert(i, j);
  21.             for (int j = 'a'; j <= 'f'; j++) insert(i, j);
  22.         }
  23.     }
  24.  
  25.     private static void insert(int i, int j) {
  26.         // ASCII values are at most 7 bits
  27.         DECODE_TABLE[i << 7 | j] = (short) (decodeNibble(i) << 4 | decodeNibble(j));
  28.     }
  29.  
  30.     private static int decodeNibble(int c) {
  31.         switch (c) {
  32.         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return c - '0';
  33.         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return  c - ('A' - 0xA);
  34.         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return c - ('a' - 0xa);
  35.         default: throw new AssertionError();
  36.         }
  37.     }
  38.  
  39.     public static byte[] decode(int offset, int len, IntUnaryOperator extractor) {
  40.         byte[] dest = new byte[len / 2];
  41.         for (int i = 0; i < dest.length; i++, offset += 2) {
  42.             dest[i] = (byte) decodeByte(extractor, offset);
  43.         }
  44.         return dest;
  45.     }
  46.  
  47.     private static short decodeByte(IntUnaryOperator extractor, int offset) {
  48.         try {
  49.             short val = DECODE_TABLE[extractor.applyAsInt(offset) << 7 | extractor.applyAsInt(offset+1)];
  50.             if(val >= 0) {
  51.                 return val;
  52.             }
  53.         } catch (ArrayIndexOutOfBoundsException ignored) {
  54.             /* fall through */
  55.         }
  56.         throw new IllegalArgumentException("invalid hex pair @ " + offset);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment