3

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?

7
  • Two reasons: 1. almost all Python numeric literals are in base 10, so 101 is one hundred and one, not five, and 2. (the exception, in Python 2.x only) a leading 0 means octal, so 0101 == 65. Therefore, to avoid confusion, bin returns a string prefixed with 0b. Commented Aug 3, 2014 at 15:17
  • Integers in Python are already stored in binary (well, technically, they're stored in either base 215 or base 230, but close enough). The internal binary is converted to a decimal string for display (e.g., by str or repr). What is it that you're trying to achieve? Commented Aug 3, 2014 at 15:42
  • Then why is it able to compute the 'str' type of binary number? Like 0b101+0b1 but not bin()+bin(). Commented Aug 3, 2014 at 15:44
  • You're thinking about this wrongly: abstractly, an integral number is just a number - it doesn't have a base. There's no such thing as a "decimal integer" or a "binary integer". There are decimal and binary representations of integers, and those are strings, not numbers. Again, what is it that you want to achieve here? What's the real problem you want to solve? Commented Aug 3, 2014 at 15:55
  • In somehow returning 'digits' in string type, isn't it interrupting further process? Commented Aug 3, 2014 at 15:59

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.