Who decided 0 means octal!?

Well, I had the whim to program late tonight, sometimes my mind is just thinking way too ‘logical’ to say no. (use of adjectival form is intended, kinda like “Think different” but sillier).

So I was programming and thinking hell of logical.

So (Kids, never begin two paragraphs in a row with “so”, or even a sentence with it, also ask your parents if you are allowed to read this if you really are a kid, I sometimes curse and reference “h - - - - p - - - “), JavaScript has a function (parseInt) to parse a string for an integer. It’s a nice function, and you can use various bases, too. (like parseInt(”10″,2) returns the integer 2, and parseInt(”10″) uses a default base of 10, and returns the integer 10).

But now, take a random guess (without having read the title of this post, hehe cheater) at what parseInt(”09″) returns. No, not 9, but rather, 0! WTF right? My thoughts of logical were upset by this event.

Turns out a ‘0′ in the beginning of a string fed to parse int means the number will be octal. Even if this is some sort of standard (although I don’t think it is true for Java… but I am not in the mood to check it out now), it is a dumb standard. I mean, this behavior is only ‘wrong’ for strings starting with “08″ and “09″, as “01″ through “07″ return 1 through 7 as valid octal strings. So it took me a while to notice it. (Incidentally it took until 2:09 as I was parsing the “09″… tee hee).

Anyways, integers in strings can often end up as “09″ without necessarily being octal, so why not use something like the “0x” used for hex. Maybe “0o” although that is confusing, or “8x” for octal… who knows.

No, it is not hard to fix. Just change it to parseInt(”09″,10) and it gets it right. But it still just feels wrong. I mean (weak argument follows) who uses octal? And, (stronger argument follows) if you are parsing both decimal and octal numbers from strings with the same line of code, your code is working its way towards unreadable, use a damn ‘if’.

Whoa, that was a rant… brb.

Leave a Comment