Python add binary number

There is an unexpected conclusion when I deal with a binary number in Python 3.

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

>>>bin(4243125)

      

Here is the problem when I try to add 2 binary functions:

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

      

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

The complement in a binary function works great:

>>>bin(x+y)

      

And try adding two binary numbers without bin () is also viable:

>>>0b100+0b10111

      

What are the reasons / goals for setting the output of bin () to a string?

+3


source to share


1 answer


bin

like hex

, converts a decimal string to a string literal representing a number in this base.

If you want to add 2 numbers together, just do this:

x = 10
y = 2
x + y

      

If you want to take binary strings as input and append them together, convert them back from string literals using int

base 2, like so:



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

      

If you want to perform bitwise operations, take a look at Python's bitwise operators:

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

+4


source







All Articles