bit operations ?

Anton Vredegoor anton at vredegoor.doge.nl
Fri Sep 20 20:17:04 CEST 2002


On Fri, 20 Sep 2002 16:40:18 +0200, "Shagshag13" <shagshag13 at yahoo.fr>
wrote:

>i'm looking for any libs which could handle bit operations on integer.
>(i must be able to get 0 to n bits from any int., only bit j, etc.)

If you're interested in setting/getting a lot of bits of a long
integer at once, this might be faster than bitshifting. I am not
guaranteeing that it is failsafe, or even that it is fast. Just hobby
programmer code I wrote when I was chasing phantoms. It works only for
long integers >= 0L now, but this should be easy to correct.

The two functions are reciprocal, so if bits are set with the setbits
function the getbits function does the reverse.

Anton.

#bitset.py test script

from time import time
import dis

#list of bit positions that are set to one
bitget ={'0' : [], '1' : [0], '2' : [1], '3' : [0,1],
         '4' : [2], '5' : [0,2], '6' : [1,2], '7' : [0,1,2],
         '8' : [3], '9' : [0,3], 'A' : [1,3], 'B' : [0,1,3],
         'C' : [2,3], 'D' : [0,2,3], 'E' : [1,2,3], 'F' : [0,1,2,3]}

#f.e. if bit at position 1 is set, '8' changes to 'A' etc.
bitset = {  '0' : ['1','2','4','8'],  '1' : ['1','3','5','9'],
            '2' : ['3','2','6','A'],  '3' : ['3','3','7','B'],
            '4' : ['5','6','4','C'],  '5' : ['5','7','5','D'],
            '6' : ['7','6','6','E'],  '7' : ['7','7','7','F'],
            '8' : ['9','A','C','8'],  '9' : ['9','B','D','9'],
            'A' : ['B','A','E','A'],  'B' : ['B','B','F','B'],
            'C' : ['D','B','E','C'],  'D' : ['D','F','D','D'],
            'E' : ['F','E','E','E'],  'F' : ['F','F','F','F'] }
                    
def setbits(ilist):
    #set bits at the positions defined in ilist,
    #returns a long integer
    dd,m = divmod(max(ilist),4)
    if m:
        dd+=1
    res = ['0'] * (dd+1)
    for x in ilist:
        d, m = divmod(x,4)
        i = dd-d
        res[i] = bitset[res[i]][m]
    return long(''.join(res),16)

def getbits(along):
    #return a list of integers corresponding to the 
    #bitpositions that are set
    h = hex(along)[2:-1]
    res = []
    i = 0
    for j in range(len(h)-1,-1,-1):
        for pos in bitget[h[j]]:
            res.append(i+pos)
        i+=4
    return res

def test():
    n =1000
    a = 2349384569856987569824652587349873498723498L
    b = getbits(a)
    t=time()
    for i in range(n):
        getbits(a)
    print time()-t
    t=time()
    for i in range(n):
        setbits(b)
    print time()-t
    print setbits(b) == a
  #  print dis.dis(setbits)
  #  print dis.dis(getbits)

if __name__ == '__main__':
    test()






More information about the Python-list mailing list