0

When I write run the following code in Python:

m = 010001110110100101110110011001010010000001101101011001010010000001100001011011100010000001000001

print "m = ", m

I receive the output:

m = 7772840013437408857694157721741838884340237826753178459792706472536593002623651807233

What's happening? Is Python automatically converting from base 2 to base 10?

hannah
  • 889
  • 4
  • 13
  • 27
  • ^There's your answer. I'll add that I partly diagnosed it by playing around in the interpreter. Just a tip. And, for binary: `m = 0b111` yields 7, for example. – keyser Apr 05 '14 at 22:11

2 Answers2

2

You're starting m with 0. Python assumes it's an Octal (see this)

What you're seeing is the decimal representation of the octal number.

If you want to work with that as binary numbers, I'd recommend setting it as an str and then parse it to int specifying that you're parsing something in base 2:

>>> m='0100011'
>>> int(m, 2)
35
Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
0

Kind of, it interprets a number starting with 0 as octal, so it actually isn't binary in the first place.

In any case, you can make it output the integer as binary like so:

print "m = ", "{0:b}".format(m)
Jacob Davis-Hansson
  • 2,603
  • 20
  • 26