Thursday, December 31, 2009

Octal or not octal, that's the question

We know hexadecimal representations of numbers in code: 0x00 for example. A less well known number representation are octal numbers. Octal numbers are in C like languages defined by prefixing a number with a 0. This can result in weird bugs, especially when not knowing this format. Not-so-surprisingly PHP adds its special confusing powers to this feature.
     0815===0 = true
010===8 = true
"010"==10 = true
"010"==8 = false
"010"=="8" = false
"010"=="10" = true
"0xf"=="15" = true
"08"=="0" = false
018==1 = true
"01"==0 = false
"0xf"=="015" = true


Tested with:
<?
function test ($exp) {
echo sprintf("%15s = %s\n",$exp,eval("return ".$exp.";")?"true":"false");
}

test("0815===0");
test("010===8"); // true
test('"010"==10'); // true
test('"010"==8'); // false
test('"010"=="8"'); // false
test('"010"=="10"'); // true
test('"0xf"=="15"');
test('"08"=="0"');
test('018==1');
test('"01"==0');
test('"0xf"=="015"');

No comments:

Post a Comment