简体   繁体   English

Python:无符号32位逐位算术

[英]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 use ctypes and its c_uint32 : 您可以使用ctypes及其c_uint32

>>> import ctypes
>>> m = 0xFFFFFF00
>>> ctypes.c_uint32(~m).value
255L

So what I did here was casting ~m to a C 32-bit unsigned integer and retrieving its value back in Python format. 所以我在这里做的是将~m转换为C 32位无符号整数并以Python格式检索其值。

You can mask everything by 0xFFFFFFFF : 您可以通过0xFFFFFFFF屏蔽所有内容:

>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
from numpy import uint32

This is a module that I created a long time ago, and it might be of help to you: 这是我很久以前创建的模块,它可能对您有所帮助:

IPv4Utils IPv4Utils

It provides at least a CIDR class with subnet arithmetic. 它至少提供带有子网算术的CIDR类。 Check the test cases at the end of the module for examples. 检查模块末尾的测试用例以获取示例。

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.

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