简体   繁体   English

java和python在逻辑运算符中给出不同的结果

[英]java and python gives different result in logical operator

I am trying to get broadcast ip address coding in Java and Python for practice. 我正在尝试使用Java和Python获得广播IP地址编码。 Here is my code in java which gives me correct output: 这是我在Java中的代码,可为我提供正确的输出:

public IPv4Address getBroadcastAddress() throws IllegalArgumentException {
    long bits = 0;
    bits = this.address.decimalIP() ^ (~(0xffffffff ^ (1L << 32 - getMaskLength()) - 1));
    IPv4Address broadcast = new IPv4Address(bits);

    return broadcast; 
}

Here decimalIP is the number representing IP address, getMaskLength - number representing its mask. 在这里, decimalIP是代表IP地址的数字, getMaskLength代表其掩码的数字。 Here I got expected broadcast address. 在这里,我得到了预期的广播地址。 By in python using the same logic I got unexpected results: 通过在python中使用相同的逻辑,我得到了意外的结果:

def broadcastaddress(self):
    return IPv4Address(self.address.decimalip ^ (~(0xffffffff ^ (1 << 32 - self.mask) - 1)))

Here all components represent the same entries as in java. 在这里,所有组件都代表与Java中相同的条目。 After debugging I got that number (~(0xffffffff ^ (1 << 32 - self.mask) - 1)) is negative. 调试后我得到那个数字(~(0xffffffff ^ (1 << 32 - self.mask) - 1))是负数。 In documents operator ~ gives inversion in bits but I don't understand why this number is negative in Python and not in Java? 在文档中,操作符~以位为单位进行求反,但我不明白为什么在Python中而不是Java中该数字为负?

Python integers are not bounded and are not signed, so ~ creates a negative number: Python整数没有边界且没有符号,因此~创建一个负数:

>>> hex(~(0xffffffff ^ (1 << 32 - 24) - 1))
'-0xffffff01'
>>> ~(0xffffffff ^ (1 << 32 - 24) - 1)
-4294967041

However, ~ in Java would give you the two's complement , while the operation on the subnet mask requires a one's complement , which can be achieved by using XOR on the netmask. 但是,在Java中, ~会给您两个补码 ,而在子网掩码上的操作需要一个补码 ,这可以通过在网络掩码上使用XOR来实现。 Since that'd undo the other XOR operation you already applied, you don't need to use the 1's complement here at all : 自那会撤消 其他 XOR您已经应用的操作,你并不需要在所有在这里使用1的补:

return IPv4Address(self.address.decimalip ^ ((1 << 32 - self.mask) - 1))

I suspect that you could just use IPv4Network.broadcast_address here: 我怀疑您可以在这里使用IPv4Network.broadcast_address

network = IPv4Network('{}/{}'.format(self.address.decimalip, self.mask)
return network.broadcast_address`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM