Skip to content

Instantly share code, notes, and snippets.

@gerner
Created December 31, 2013 19:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerner/8201345 to your computer and use it in GitHub Desktop.
Save gerner/8201345 to your computer and use it in GitHub Desktop.
Hex decoding/encoding
public class HexDecoder {
//lower ascii only
private static int[] HEX_TO_INT = new int[] {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //0-15
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //16-31
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //32-47
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, //48-63
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, //64-79
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //80-95
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, //96-111
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 //111-127
};
public static byte[] decode(String s) {
char[] c = s.toCharArray();
int len = c.length;
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) (((HEX_TO_INT[(int)c[i]]) << 4)
+ HEX_TO_INT[(int)c[i+1]]);
}
return data;
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String encode(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static void main(String[] args) {
System.out.println(encode(decode(args[0])));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment