help in obtaining binary equivalent of a decimal number in python
Dave Angel
davea at davea.name
Thu May 23 07:55:36 EDT 2013
On 05/23/2013 07:30 AM, lokeshkoppaka at gmail.com wrote:
> 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.
--
DaveA
More information about the Python-list
mailing list