nobody
nobody

Reputation: 414

python adding binary number

There is an unexpected output when I am dealing with binary number in Python 3.

We can easily convert any integer to binary by built-in bin() function. For example:

>>>bin(4243125)

Here's the issue when I try to add 2 binary function:

>>>bin(x)+bin(y)

The output is concatenation of two binary number, not addition of binary number. The output of binary function has become a string.

Addition in a binary function works fine:

>>>bin(x+y)

And try to add two binary number without bin() is viable too:

>>>0b100+0b10111

What is the reasons/purposes of setting a bin() output to a string?

Upvotes: 3

Views: 11004

Answers (1)

stderr
stderr

Reputation: 8722

bin, like hex, converts a decimal to a string literal representing the number in that base.

If you want to add 2 numbers together simply do so:

x = 10
y = 2
x + y

If you want to take binary strings as input and add them together convert them back from string literals with int base 2, like this:

x = bin(10)
y = bin(2)
int(x, 2) + int(y, 2)

If you're looking to do bitwise operations look at the Python bitwise operators:

https://wiki.python.org/moin/BitwiseOperators

Upvotes: 4

Related Questions