Python: unsigned 32 bit bitwise arithmetic

前端 未结 5 1746
花落未央
花落未央 2020-12-05 17:31

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,

相关标签:
5条回答
  • 2020-12-05 17:55

    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.

    0 讨论(0)
  • 2020-12-05 18:01

    You can mask everything by 0xFFFFFFFF:

    >>> m = 0xFFFFFF00
    >>> allf = 0xFFFFFFFF
    >>> ~m & allf
    255L
    
    0 讨论(0)
  • 2020-12-05 18:10

    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.

    0 讨论(0)
  • 2020-12-05 18:12
    from numpy import uint32
    
    0 讨论(0)
  • 2020-12-05 18:16

    You could also xor with 0xFFFFFFFF, which is equivalent to the "unsigned complement".

    >>> 0xFFFFFF00 ^ 0xFFFFFFFF
    255
    
    0 讨论(0)
提交回复
热议问题