[英]Python: unsigned 32 bit bitwise arithmetic
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic. 试图回答其解决方案涉及IP地址和网络掩码的另一篇文章,我陷入了简单的按位算法。
Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]? 在Python中是否有一种标准方法可以进行按位AND,OR,XOR,NOT运算,假设输入为“32位”(可能是负数)整数或长整数,并且结果必须是范围内的长整数[ 0,2 ** 32]?
In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs. 换句话说,我需要一个有效的Python对应于无符号长整数之间的C位运算。
EDIT: the specific issue is this: 编辑:具体问题是:
>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
You can mask everything by 0xFFFFFFFF
: 您可以通过0xFFFFFFFF
屏蔽所有内容:
>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
from numpy import uint32
You could also xor with 0xFFFFFFFF, which is equivalent to the "unsigned complement". 您还可以使用0xFFFFFFFF进行xor,这相当于“unsigned complement”。
>>> 0xFFFFFF00 ^ 0xFFFFFFFF
255
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.