When:
byte[] b = {-128, 0, 0, 0};
long total = 0;
The first expression returns -2,147,483,648:
for (int i = 0; i < b.length; i++) {
int shift = (b.length - 1 - i) * 8;
total += (b[i] & 255) << shift;
}
The second returns 2,147,483,648:
for (int i = 0; i < b.length; i++) {
int shift = (b.length - 1 - i) * 8;
long tmp = (b[i] & 255);
total += tmp << shift;
}
My question is; why is the first statement positive and the second negative when they appear to be the same statement?
In this line
the parenthesized expression is of type
intand the left shift sets its leftmost bit to one, making it a negative number. The conversion tolonghappens only after all the calculation is done.Here the expression is
longand the leftmost bit will stay zero after the shift.If you want to keep the first expression, just add a cast to
longfor the parenthesized expression or use alongconstant255L.