Skip to content

Instantly share code, notes, and snippets.

@xZise
Created April 12, 2012 17:42
Show Gist options
  • Select an option

  • Save xZise/2369546 to your computer and use it in GitHub Desktop.

Select an option

Save xZise/2369546 to your computer and use it in GitHub Desktop.
Faster String → Long conversion
public static Long tryAndGetLong(String string, int radix) {
try {
return Long.parseLong(string, radix);
} catch (NumberFormatException e) {
return null;
}
}
private static final String DIGITS = "0123456789";
private static final String UPPER_DIGIT_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWER_DIGIT_MAP = "abcdefghijklmnopqrstuvwxyz";
public static Long speedLongParse(final String string, final int radix) {
final char[] chars = string.toCharArray();
int i = chars[0] == '-' ? 1 : 0;
for (;i < chars.length; i++) {
final char c = chars[i];
final int digitIdx = DIGITS.indexOf(c);
if (digitIdx >= radix) {
return null;
}
final int upperIdx = UPPER_DIGIT_MAP.indexOf(c);
if (upperIdx >= radix - 10) {
return null;
}
final int lowerIdx = LOWER_DIGIT_MAP.indexOf(c);
if (lowerIdx >= radix - 10) {
return null;
}
if (digitIdx < 0 && upperIdx < 0 && lowerIdx < 0) {
return null;
}
}
// Should never return null
return tryAndGetLong(string, radix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment