In Java String Integer::toString(long i, int radix)
returns representation of number i
using given radix(base). Before it does conversion it is mapping number i
to -i
:
byte[] buf = new byte[65];
int charPos = 64;
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = (byte)Integer.digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = (byte)Integer.digits[(int)(-i)];
I do not understand why it works with negative number instead of positive. In Java x % y = -((-x) % y)
so it is confusing to me because it should not do any difference because result of modulo operation is negated in the code.
The code doesn't want to handle positive and negative values differently, so it wants to unify the sign.
The most obvious normalization would be to convert negative value to positive. That's what we humans would do. But, with numbers stored in two's compliment, the value range of negative numbers it one larger than the value range of positive numbers, so if we normalized to positive, it would fail for -2147483648
, aka Integer.MIN_VALUE
.