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

Asked

Viewed 148 times

9

You could tell me why when I type on the console 010 and press enter it returns to me 8 ? and if I type 0100 he returns me 64.

2 answers

11


When Chrome interprets a number starting with the character 0 he makes it as being an octal.

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

What is octal representation

It’s a numbering system, just like there’s decimal, hexadecimal, only base 8. Other numbering systems may also have special characters to represent them.

  • binary: base 2 (has no representation)

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

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

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

How the conversion is made

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

Code to illustrate how the conversion works (note that javascript already provides methods capable of making these conversions, my intention is to show the operation):

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;
}

From decimal to octal

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

5

The browser is making a DECIMAL to OCTAL conversion

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

And so on. Remembering that 010 is equivalent to 10, as well as 0100 is equal to 100.


How to make a Decimal calculation for Octal?

1985 / 8

385 248 / 8

65 08 31 / 8

1 0 7 3

1 is the rest of the division. MOD 0 is the rest of the division. MOD 7 is the rest of the division. MOD 3 is the result of the division. /

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

Wikipedia Conversions - Octal

Browser other questions tagged

You are not signed in. Login or sign up in order to post.