Skip to content

Instantly share code, notes, and snippets.

@socram8888
Last active December 23, 2015 06:09
Show Gist options
  • Save socram8888/6591712 to your computer and use it in GitHub Desktop.
Save socram8888/6591712 to your computer and use it in GitHub Desktop.
Fastest byte-to-hex function I could program
// Marcos Vives Del Sol - 17/IX/2013
// License: WTFPL
import java.lang.reflect.Constructor;
public class FastHex {
private static Constructor<String> STRING_CONSTRUCTOR = null;
private static final char[] HEX_CHAR = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static final String hex(byte[] data) {
// Cache to reduce field access
char[] hexchars = HEX_CHAR;
// Char array that can hold the double of the data length (two hex chars per byte)
char[] chars = new char[data.length << 1];
for (int i = 0; i < data.length; i++) {
chars[i << 1] = hexchars[(data[i] >> 4) & 0xF];
chars[(i << 1) + 1] = hexchars[data[i] & 0xF];
};
Constructor<String> constructor = STRING_CONSTRUCTOR;
if (constructor != null) {
try {
return constructor.newInstance(0, chars.length, chars);
} catch (Exception e) { };
};
// Fallback to a version that copies the array
return new String(chars);
};
static {
try {
// Attempt to get a handle to the string constructor which does not clone the array
Constructor<String> constructor = String.class.getDeclaredConstructor(int.class, int.class, char[].class);
constructor.setAccessible(true);
STRING_CONSTRUCTOR = constructor;
} catch (Exception e) { };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment