I am given a large integer a
, and a (relatively small) integer n
.
What is the fastest way to get the n
th bit (from the right) of the binary decomposition of a
using Python? (I do not want to write a C pluggin, just plain Python.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With