Bitwise operations in Python

给你一囗甜甜゛ 提交于 2019-12-06 07:15:42

问题


I'm looking for recommendations on how to do bitwise math in python.

The main problem I have is that python's bitwise operators have infinite precision, which means that -1 is really "111.......111". That's not what I want. I want to emulate real hardware which will have some fixed precision, say 32 bits.

Here are some gotchas:

1) -n should return a 32 bit 2's complement number ( this is easily achieved by taking the lower 32 bits of the infinite precision -n )

2) n >> 3, should be an arithmetic shift of a 32 bit number, which means if bit 31 is '1', then bits 31:28 should be '1' after the shift by 3.


回答1:


You could always add a & ((1<<32) - 1) mask to limit the number to 32-bits before performing any operation, e.g.

class Int32(int):
    def __neg__(self):
        return Int32(int.__neg__(self) & ((1 << 32) - 1))
    def __rshift__(self, other):
        if self & (-1 << 31):
             retval = int.__rshift__(int.__sub__(self, 1<<32), other)
             return Int32(retval & ((1 << 32) - 1))
        else:
             return Int32(int.__rshift__(self, other))
    ...

>>> -Int32(5)
4294967291
>>> (-Int32(5)) >> 1
4294967293



回答2:


You could use numpy, it has built in int32 types and much more.



来源:https://stackoverflow.com/questions/5994307/bitwise-operations-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!