help in obtaining binary equivalent of a decimal number in python

L

lokeshkoppaka

i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's
For Example
if the input is 2
Output should be:
the 32bit equivalent of 2 :0000 0000 0000 0000 0000 0000 0000 0010
and the 1's compliment is:1111 1111 1111 1111 1111 1111 1111 1101



is there any pre-defined function to get the above results in python??
 
C

Chris Angelico

i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's
For Example
if the input is 2
Output should be:
the 32bit equivalent of 2 :0000 0000 0000 0000 0000 0000 0000 0010
and the 1's compliment is:1111 1111 1111 1111 1111 1111 1111 1101



is there any pre-defined function to get the above results in python??

You're asking for bitwise negation. Now that you know the keyword(s)
to look for, you should be able to figure out the rest with a few
quick docs and/or web searches.

ChrisA
 
D

Dave Angel

i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's
For Example
if the input is 2
Output should be:
the 32bit equivalent of 2 :0000 0000 0000 0000 0000 0000 0000 0010
and the 1's compliment is:1111 1111 1111 1111 1111 1111 1111 1101



is there any pre-defined function to get the above results in python??

I'm curious as to the intent of the assignment. Are you supposed to be
learning about base conversion, about ones and twos complement, or about
Python?

Assuming the intent is to learn about Python, the built-in function
bin() will take a Python integer (which is not decimal) and convert it
to a str. At that point, you can manipulate the string any way you like.

x = 45
print bin(45)
0b101101


Perhaps you want to start by stripping off the leading '0b' using a
slice. Then you want to pad it to 32 columns by prepending some number
of zeroes. Then you want to insert some spaces at regular intervals.

Presumably doing the ones-complement operation on that string is then
pretty easy for you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top