How do I manipulate bits in Python?

后端 未结 9 1886
借酒劲吻你
借酒劲吻你 2020-12-12 22:37

In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:

unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
9条回答
  •  旧时难觅i
    2020-12-12 23:07

    If you're going to do a lot of bit manipulation ( and you care much more about readability rather than performance for your application ) then you may want to create an integer wrapper to enable slicing like in Verilog or VHDL:

     import math
     class BitVector:
         def __init__(self,val):
             self._val = val
    
         def __setslice__(self,highIndx,lowIndx,newVal):
             assert math.ceil(math.log(newVal)/math.log(2)) <= (highIndx-lowIndx+1)
    
             # clear out bit slice
             clean_mask = (2**(highIndx+1)-1)^(2**(lowIndx)-1)
    
             self._val = self._val ^ (self._val & clean_mask)
             # set new value
             self._val = self._val | (newVal<>lowIndx)&(2L**(highIndx-lowIndx+1)-1)
    
     b = BitVector(0)
     b[3:0]   = 0xD
     b[7:4]   = 0xE
     b[11:8]  = 0xA
     b[15:12] = 0xD
    
     for i in xrange(0,16,4):
         print '%X'%b[i+3:i]
    

    Outputs:

     D
     E
     A
     D
    

提交回复
热议问题