Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.
Is there a standard way, in Python,
You can use ctypes and its 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.
You can mask everything by 0xFFFFFFFF
:
>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
This is a module that I created a long time ago, and it might be of help to you:
IPv4Utils
It provides at least a CIDR
class with subnet arithmetic. Check the test cases at the end of the module for examples.
from numpy import uint32
You could also xor with 0xFFFFFFFF, which is equivalent to the "unsigned complement".
>>> 0xFFFFFF00 ^ 0xFFFFFFFF
255