Python:无符号32位按位算术 [英] Python: unsigned 32 bit bitwise arithmetic
问题描述
尝试回答另一篇有关其解决方案涉及IP地址和网络掩码的文章时,我陷入了普通的按位算法.
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.
在Python中,是否存在一种标准的方式来进行按位AND,OR,XOR,NOT运算,假设输入是"32位"(可能是负数)整数或long,并且结果必须是long in范围[0,2 ** 32]?
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]?
换句话说,我需要一个与无符号长整数之间的C按位运算有效的Python副本.
In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.
具体问题是这样:
>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
推荐答案
您可以通过0xFFFFFFFF
屏蔽所有内容:
You can mask everything by 0xFFFFFFFF
:
>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
这篇关于Python:无符号32位按位算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!