23

I've always wondered why leading zeroes (0) are used to represent octal numbers, instead of — for example — 0o. The use of 0o would be just as helpful, but would not cause as many problems as leading 0es (e.g. parseInt('08'); in JavaScript). What are the reason(s) behind this design choice?

Pops
  • 30,199
  • 37
  • 136
  • 151
Hauleth
  • 22,873
  • 4
  • 61
  • 112

3 Answers3

28

All modern languages import this convention from C, which imported it from B, which imported it from BCPL.

Except BCPL used #1234 for octal and #x1234 for hexadecimal. B has departed from this convention because # was an unary operator in B (integer to floating point conversion), so #1234 could not be used, and # as a base indicator was replaced with 0.

The designers of B tried to make the syntax very compact. I guess this is the reason they did not use a two-character prefix.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
3

Worth noting that in Python 3.0, they decided that octal literals must be prefixed with '0o' and the old '0' prefix became a SyntaxError, for the exact reasons you mention in your question

https://www.python.org/dev/peps/pep-3127/#removal-of-old-octal-syntax

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
1

"0b" is often used for binary rather than for octal. The leading "0" is, I suspect for "O -ctal".

If you know you are going to be parsing octal then use parseInt('08', 10); to make it treat the number as base ten.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • Yeah, I know. I'm only wondering why it is used, because it's a little bit confusing for newbies. With `0b` I've made a mistake, fixed to `0o`. – Hauleth Jul 14 '12 at 11:18
  • "Zero" as in "octal"? Hardly. My speculation would be that it was simply the prevalent number format of the day, much like hex is now. – tripleee Jul 14 '12 at 12:10
  • @triplee: You do realize 0 looks like an O, right? It's not like people haven't been replacing 13773rs with numbers for y34rs. – Brent Rittenhouse Nov 01 '17 at 20:50