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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
If
not not(foo)freaks you out, or you really want anintanswer instead of abool, you can use1 if foo else 0; it’s only slightly slower.