Get n-th bit of an integer

Question:

I am given a large integer a, and a (relatively small) integer n.

What is the fastest way to get the nth bit (from the right) of the binary representation of a using native Python?

Asked By: Randomblue

||

Answers:

Shift the bit to the last position, mask out everthing else:

bit = (a >> n) & 1

This assumes that the bits are indexed in the usual way, i.e. the least significant bit is bit 0.

Edit: I’m not sure if this is the fastest way to do it in your version of Python, but at least it is the most straight-forward way. Depending on your Python version and the particular values of a and n, there might be faster ways, as shown in the answer by John Machin.

Answered By: Sven Marnach

You asked for the fastest way, presumably using a modern version of Python. Modern versions of Python have variable-length ints, and conventional wisdom does’t apply. Shifting a large number is not cheap. Shifting 1 is cheap. Here are some -mtimeit inputs and corresponding outputs. The first is an abbreviation of

windows command prompt>python27python -mtimeit -s"a=10**20;n=3" "(a>>n)&1"
1000000 loops, best of 3: 0.238 usec per loop

-s"a=10**20;n=3" "(a>>n)&1"
0.238 usec 

-s"a=10**20;n=3" "not not(a & (1 << n))"
0.154 usec 

-s"a=10**200;n=3" "(a>>n)&1"
0.382 usec 

-s"a=10**200;n=3" "not not(a & (1 << n))"
0.155 usec 

-s"a=10**10;n=3" "(a>>n)&1"
0.231 usec 

-s"a=10**10;n=3" "not not(a & (1 << n))"
0.156 usec 

-s"a=10**9;n=3" "(a>>n)&1"
0.0801 usec

-s"a=10**9;n=3" "not not(a & (1 << n))"
0.0938 usec

-s"a=2**1000;n=64" "(a>>n)&1"
0.446 usec

-s"a=2**1000;n=64" "not not(a & (1 << n))"
0.255 usec

If not not(foo) freaks you out, or you really want an int answer instead of a bool, you can use 1 if foo else 0; it’s only slightly slower.

Answered By: John Machin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.