Java – bitwise OP unexpectedly becomes negative
Can someone explain to me why I got these results?
public static int ipv4ToInt(String address) { int result = 0; // iterate over each octet for(String part : address.split(Pattern.quote("."))) { // shift the prevIoUsly parsed bits over by 1 byte result = result << 8; System.out.printf("shift = %d\n",result); // set the low order bits to the current octet result |= Integer.parseInt(part); System.out.printf("result = %d\n",result); } return result; }
For IPv4 toint ("10.35.41.134"), I get:
This is the same as the result I got when I did my own mathematical calculation
For IPv4 toint ("192.168.0.1"), I get:
For this, when I do the math manually, I get 3232235521
Interestingly: 3232235521 = 11000000010101000000000000000000 1 when I enter 1062731775 to enter my windows Calc and press the / – button, I get: - 1062731775 = 11111111111111111111111111111 110000000101010000000000000000 1
This function still works for my purpose, but I'm really curious. Why does the earth result become negative when I make the last conversion?
Solution
Because your situation overflows!
In Java, integers are also 32 bits, ranging from - 2147483648 to 2647
12625920 < < 8 crosses the limit of 2 ^ 31-1, so the result becomes negative The result is just a flip from the - ve side, so any range left from the positive is accompanied by so much from the negative! As suggested, you should use the long variable to avoid overflow!