Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - binary numbers?

I am using the python shell to figure out how the print command works in python.
When I type in

print 01
1
print 010
8
print 0100
64
print 030
24

What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shouldn't it be 2 if it's binary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Starting a number with a zero marks it as octal in Python 2. This has been recognized as confusing, surprising and also inconsistent, as starting with 0x will mark it as hexadecimal. Therefore, in Python 3, starting with 0 is invalid, and you get octal by starting with 0o. You can also start with 0b to mark it as binary.

>>> 10
10
>>> 0x10
16
>>> 0o10
8
>>> 0b10
2
>>> 010
  File "<stdin>", line 1
    010
      ^
SyntaxError: invalid token

0x, 0o and 0b also works in Python 2.6 and Python 2.7.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...