2010-11-16 75 views

回答

3

一種方法是使用BitVector庫。使用

例子:

>>> from BitVector import BitVector 
>>> bv = BitVector(intVal = 0x13A5, size = 32) 
>>> print bv 
00000000000000000001001110100101 
>>> bv << 6       #does a cyclic left shift 
>>> print bv 
00000000000001001110100101000000 
>>> bv[0] = 1 
>>> print bv 
10000000000001001110100101000000 
>>> bv << 3       #cyclic shift again, should be more apparent 
>>> print bv 
00000000001001110100101000000100 
+7

所以''<<操作就地修改自己的包裝類?我認爲這肯定是一個錯字,你的意思是寫'<< ='但你的代碼是正確的。那裏有可疑的設計選擇。 – 2010-11-17 10:31:17

2

的一個循環左移8位掩碼:

shifted = number << 1 
overflowed = (number & 0x100) >> 8 
shifted &= 0xFF 
result = overflowed | shifted 

您應該能夠使一個類,這是否適合你。再多一點,它可以將任意數量的值移出任意大小的值。

1

如果你想有一個數的低32位,可使用二進制和像這樣:

>>> low32 = (1 << 32) - 1 
>>> n = 0x12345678 
>>> m = ((n << 20) | (n >> 12)) & low32 
>>> "0x%x" % m 
'0x67812345' 
2

bitstring模塊可能會有所幫助(文檔here)。這個例子創建一個22位比特串,並旋轉位3到右:

>>> from bitstring import BitArray 
>>> a = BitArray(22) # creates 22-bit zeroed bitstring 
>>> a.uint = 12345  # set the bits with an unsigned integer 
>>> a.bin    # view the binary representation 
'0b0000000011000000111001' 
>>> a.ror(3)   # rotate to the right 
>>> a.bin 
'0b0010000000011000000111' 
>>> a.uint    # and back to the integer representation 
525831 
+0

感謝您的包裝。 :) – gorlum0 2011-09-05 08:44:23