在Python位操作 [英] Bitwise operations in Python
问题描述
我在寻找如何在蟒蛇做按位数学的建议。
我的主要问题是Python的位运算符有无限的precision,这意味着-1真是111 ....... 111。这不是我想要的。我想效仿,这将有一些固定的precision真实的硬件,说32位。
下面是一些陷阱:
1)-n应该返回一个32位2的补数(这是很容易通过采取无限precision -n的低32位实现)
2)N >> 3,应该是一个32比特数的算术移位,这意味着如果位31为1,则位3后移31:28应该是'1'。对>
您可以随时添加一个&安培; ((1 <<;&LT; 32) - 1)。
面膜进行任何操作,例如之前限制到32位的数量
类的Int32(INT):
高清__neg __(个体经营):
返回的Int32(中间体.__负__(个体)及((1 <<;&下; 32) - 1))
高清__rshift __(自我,其他的):
如果自我和放大器; (-1下;&下; 31):
RETVAL = INT .__ RSHIFT __(INT .__分__(自我,1 LT;&LT; 32),其他)
返回的Int32(RETVAL及((1 <<;&下; 32) - 1))
其他:
返回的Int32(INT .__ RSHIFT __(自我,其他))
...&GT;&GT;&GT; -Int32(5)
4294967291
&GT;&GT;&GT; (-Int32(5))&GT;&GT; 1
4294967293
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.
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
这篇关于在Python位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!