gor*_*non 3 java bit-manipulation
有人可以向我解释为什么我得到这些结果?
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;
}
Run Code Online (Sandbox Code Playgroud)
对于ipv4ToInt("10.35.41.134"),我得到:
shift = 0
result = 10
shift = 2560
result = 2595
shift = 664320
result = 664361
shift = 170076416
result = 170076550
10.35.41.134 = 170076550
这与我自己进行数学计算时得到的结果相同.
对于ipv4ToInt("192.168.0.1"),我得到:
shift = 0
result = 192
shift = 49152
result = 49320
shift = 12625920
result = 12625920
shift = -1062731776
result = -1062731775
192.168.0.1 = -1062731775
对于这个,当我手动进行数学运算时,我得到3232235521.
有趣的是:
3232235521 = 11000000101010000000000000000001
当我输入1062731775进入我的Windows计算并点击+/-按钮时,我得到:
-1062731775 = 11111111111111111111111111111111 11000000101010000000000000000001
该功能仍然适用于我的目的,但我真的很好奇,为什么当我做最后一点转换时为什么地球结果会变为负值?
因为你的情况下位溢出!
在Java中,整数也是32位,范围是-2,147,483,648到2,147,483,647.
12625920 << 8 超过2 ^ 31-1的限制因此,结果变为负面...
结果只是从-ve侧翻转,因此,从正面留下的任何范围都伴随着来自负面的那么多!
正如大家所建议的那样,你应该使用long变量来避免溢出!