Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: help in obtaining binary equivalent of a decimal number in python

14 views
Skip to first unread message
Message has been deleted

Chris Angelico

unread,
May 23, 2013, 7:37:30 AM5/23/13
to pytho...@python.org
On Thu, May 23, 2013 at 9:30 PM, <lokesh...@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??

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

Dave Angel

unread,
May 23, 2013, 7:55:36 AM5/23/13
to pytho...@python.org
On 05/23/2013 07:30 AM, lokesh...@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
0 new messages