Why does the Chrome console return 8 when I type 010?

5

Would you know to tell me why when I type in the console 010 and press enter it returns me 8 ? and if I type 0100 it returns me 64 .

    
asked by anonymous 26.03.2014 / 21:02

2 answers

7

When Chrome interprets a number starting with the character 0 , it does it as an octal.

The octal representation of the number 8 (decimal) is 010 , and the octal representation of the number 64 (decimal) is 0100 .

What is octal representation

It is a numbering system, just as there is the decimal, the hexadecimal, only in the base 8. The other numbering systems may also have special characters to represent them.

  • binary: base 2 (no representation)

  • octal: base 8 (represented by beginning the number by 0 )

  • decimal: base 10 (represented beginning with any number other than 0 )

  • hexadecimal: base 16 (can be represented by starting with 0x )

How conversion is done

The most complicated conversion is between octal / decimal, since the bases are not multiple.

Code to illustrate how the conversion works (note that javascript already provides methods that can do these conversions, my intention is to show how it works):

From octal to decimal

function ConverterOctalParaNumero(txt)
{
    var result = 0, mul = 1;
    for (var i = 0; i < txt.length; i++){
        var ch = txt[txt.length - i - 1];
        result += ch * mul;
        mul *= 8;
    }
    return result;
}

Decimal to octal

function ConverterNumeroParaOctal(num)
{
    var result = "";
    while (num > 0){
        result = "01234567"[num % 8] + result;
        num = Math.floor(num / 8);
    }
    return result;
}
    
26.03.2014 / 21:24
2

The browser is doing a conversion from DECIMAL to OCTAL

Decimal to octal : 10 is 8 ; 100 is 64 ; 45 is 55 .

And so it goes. Remembering that 010 is equivalent to 10 , as 0100 equals 100 .

How to make a Decimal to Octal calculation?

1985/8

1 0 7 3

1 is remainder of the split. Mod 0 is remainder of the division. Mod 7 is remainder of the division. Mod 3 is the result of division. /

In this example you should read the number backwards. 3701 conversion from decimal to binary is similar.

Wikipedia Conversions - Octal

    
26.03.2014 / 21:23