6

How to convert a int n into binary and test each bit of the resulting binary number?

I have just got the following after a lot of googling:

def check_bit_positions(n, p1, p2):
    print int(str(n),2)

However i get an error invalid literal for int() with base 2. Let me know how can i get binary form of the input number and test each bit at position p1 and p2

EDIT:

binary = '{0:b}'.format(n)
if list(binary)[p1] == list(binary)[p2]:
     print "true"
 else:
     print "false"

The above code works now, however how can i check for postions p1 and p2 from the end of the list?

5
  • What are you trying to do exactly? Test if certain bits are on? Commented Aug 7, 2013 at 19:02
  • @arshajii Yes, and i want to know how to test at indexes from the start and end of the list. Please see my update. Commented Aug 7, 2013 at 19:05
  • You can back-index lists with negative indexes. l[-1] is the last element of l, l[-2] is the second to last etc.. Commented Aug 7, 2013 at 19:06
  • @TinaS you can use negative indexes: binary[-p1] == binary[-p2]. And There's no need to convert a string to list, a string is iterable in python. Commented Aug 7, 2013 at 19:06
  • 'binary' is really just a string and can be used without wrapping it in a list. Try binary[p1] == binary[p2] without list-izing it. Commented Aug 7, 2013 at 23:02

3 Answers 3

7

Use bin() function:

>>> bin(5)
'0b101'

or str.format:

>>> '{0:04b}'.format(5)
'0101'
Sign up to request clarification or add additional context in comments.

6 Comments

If you don't want the leading 0b, then use bin(s)[2:]
Thanks @RohitJain, can you even help me on how to check the list from the end, i.e position p from the end of a list. Also i cannot upvote due to low reputation.
@TinaS. You can use negative indices - s[-1] == s1[-1]. And you don't need to convert it to list. You can use indices on string too.
I have one more generic question, How can i know all the constructs of the language. As in i can see most of the answers here are using very less and optimised code, however i seem to write lengthy code due to my beginner level knowledge. Do you have any useful tips?
@TinaS You can start from official Python Tutorial. Also Python Language Reference can be handy.
|
6

Here's a quick function I wrote to check the nth bit of a number:

def check_nth_bit(num, n):
    return (num>>n)&1

Basically, you bitshift the number n times to the right, which would put the nth digit in the rightmost position, and by bitwise and-ing the new number with 1 (which is all 0's except for in the rightmost position), you can check if that bit is a 1 or a 0. So, you can call this function on num with p1 and p2 and compare the results.

EDIT: This will be p1 and p2 from the end of the number (least-significant bit), not the beginning.

1 Comment

Thanks for your answer, but i will go with one of the above mentioned answers as it suits my current needs. However i will use your method as a helper function for future use.
3

You can use format:

>>> format(10, 'b')
'1010'

int is used to convert a number from any base to base 10, and you're trying to use it to convert an integer to binary which is wrong.

>>> int('1010', 2)
10
>>> int('20', 2)
Traceback (most recent call last):
  File "<ipython-input-3-05fc7296a37e>", line 1, in <module>
    int('20', 2)
ValueError: invalid literal for int() with base 2: '20'

6 Comments

Thanks @Ashwini , i combined @Rohit and your answer and able to proceed. Could you please update me on how to test a list element at a index p from end.
@AshwiniChaudhary You have linked the same question in the comment.
@TinaS I linked my comment not question. I posted that comment on your question before your comment on my answer.
@AshwiniChaudhary Thanks for your time and effort. I can accept only one answer though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.