Why does this code sometimes produce ArrayOutOfBoundsException? How is that even possible for String.valueOf(int)
?
public static String ipToString(B
I am leaving the code snippet here, as it still ought to be run faster than the original code - at a cost of memory - but be advised it doesn't actually fix the problem.
private static final String[] STRING_CACHE = new String[256];
static {
for(int i = 0; i <= 255; i++) {
STRING_CACHE[i] = String.valueOf(i);
}
}
public static String ipToString(ByteString bs) {
if (bs == null || bs.isEmpty()) {
return null;
} else {
StringBuilder sb = new StringBuilder();
boolean started = false;
for (Byte byt : bs) {
if (started) {
sb.append(".");
}
sb.append(STRING_CACHE[byt & 0xFF]);
started = true;
}
return sb.toString();
}
}