Last active
December 23, 2015 06:09
-
-
Save socram8888/6591712 to your computer and use it in GitHub Desktop.
Fastest byte-to-hex function I could program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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