Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get n-th bit precision of integer

Tags:

python

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 decomposition of a using Python? (I do not want to write a C pluggin, just plain Python.)

like image 203
Randomblue Avatar asked Dec 01 '22 00:12

Randomblue


1 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.

like image 151
Sven Marnach Avatar answered Dec 06 '22 08:12

Sven Marnach