Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to iterate over bits of integer

Let's a=109 or 1101101 in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1]

like image 446
dmzkrsk Avatar asked Jan 17 '12 17:01

dmzkrsk


People also ask

Can you iterate over an integer?

Not all objects can be iterated, for example - we cannot iterate an integer, it is a singular value.

How do you extract bits from integers in Python?

*/ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character. Step 3 : then extracting k bits from starting position pos from right.so, the ending index of the extracting substring is e=len(bi)-pos and starting index=e-k+1 Step 4 : extract k bit sub-string.

What can you iterate over in Python?

These include the string, list, tuple, dict, set, and frozenset types. But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules are designed to be iterable. For example, open files in Python are iterable.


2 Answers

There's a trick for just getting the 1's out of the binary representation without having to iterate over all the intervening 0's:

def bits(n):     while n:         b = n & (~n+1)         yield b         n ^= b   >>> for b in bits(109):     print(b)   1 4 8 32 64 
like image 130
Duncan Avatar answered Sep 20 '22 20:09

Duncan


My approach:

def bits(number):     bit = 1     while number >= bit:        if number & bit:            yield bit        bit <<= 1 

I don't think there is a builtin function for it.

I also wonder if there isn't a better approach to whatever you are doing. There's a good chance you don't really want to iterate over the bits like this. They may be a much better way.

Out of curiosity I ran some timing on the methods posted here, my results:

Winston 2.35238099098 F.J. 6.21106815338 F.J. (2) 5.21456193924 Sven 2.90593099594 Duncan 2.33568000793 freegnu 4.67035484314 

F.J. converts to a string, I'm guessing that hurts his performance. The various optimisation attempts help, but not enough Sven produces the reverse of everybody else, which might be an advantage if you really needed that. Duncan's approach wins speedwise (just barely)

Again with 340282366920938463463374607431768211457 instead of 109:

Winston 44.5073108673 F.J. 74.7332041264 Sven 47.6416211128 Duncan 2.58612513542 

Nice, Duncan! It should be noted that this is pretty much the best case for Duncan's method, so it won't always have this dramatic an advantage.

like image 29
Winston Ewert Avatar answered Sep 16 '22 20:09

Winston Ewert