0

I wonder why adding one or multiple leading zeros to an integer in Python leads to different results when using the bitshift-operators:

In:  10<<1
Out: 20

Adding a "0" in front of the integer:

In:  010<<1
Out: 16
BHawk
  • 2,382
  • 1
  • 16
  • 24
dorvak
  • 9,219
  • 4
  • 34
  • 43

1 Answers1

2

Meanwhile, I found the answer is quite simple - but maybe it's worth sharing it:

According to this answer, adding a leading zero to an integer will cause Python to interpret it as an octal/base 8.

In:  int("010",8)
Out: 8

Thus, left-shifting the octal (or decimal 8), i.e. multipicaton by 2**1, leads to 16

In:  8<<1
Out: 16
Community
  • 1
  • 1
dorvak
  • 9,219
  • 4
  • 34
  • 43
  • If you already found an answer, why did you post a self-answered question? That's just creating a duplicate. – Martijn Pieters May 14 '14 at 13:07
  • I wouldn't say that it creates a duplicate. See http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ (In fact, there is an option to answer your own question). – dorvak May 14 '14 at 13:26
  • Yes, you can answer your own question, but that doesn't mean you need to create one for each and every situation where you can use an octal number literal. – Martijn Pieters May 14 '14 at 13:28
  • It is not the act of self-answering that I am protesting here! Note that the two questions on my profile are self-answers too. – Martijn Pieters May 14 '14 at 13:28