bit manipulation - Python How to get set bit -
say have number in memory looks (or similar, don't know how python stores numbers):
0000 0000 0000 1000
i want bit set (thanks @muddyfish, clarify these numbers have 1 bit set), in case 3, because 2^3 = 8. use log2 achieve this, seems solved 'bit twiddling' techniques. loop through bits this:
def getsetbit(num): if num == 0: return -1 bit = 0 while num != 1: bit += 1 num >>= 1 return bit # getbitset(0b100000) == 5 # getbitset(1) == 0
however me seems awkward , slower should be. if way this, guess live it, if wasn't.
to bit number of highest bit set, use
int.bit_length()-1
this more efficient using math.log()
or other function had posted
edit:
as requested, timeit results posted:
python -m timeit -s 'import math;x=100' 'int(math.log(x,2))'
1000000 loops, best of 3: 0.5 usec per loop
python -m timeit -s 'i = 100' 'i.bit_length()-1'
10000000 loops, best of 3: 0.106 usec per loop
also, using math.log
yeild inaccurate results values higher 2**29.
Comments
Post a Comment