[ACCEPTED]-Get n-th bit precision of integer-python

Accepted answer
Score: 13

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

bit = (a >> n) & 1

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

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

Score: 6

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

windows command prompt>\python27\python -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 2 you really want an int answer instead of a 1 bool, you can use 1 if foo else 0; it's only slightly slower.

More Related questions