Search code examples
c++octal

C++ cout output explanation please


Possible Duplicate:
why is initializing an integer in VC++ to 010 different from initialising it to 10?

This got me very confused, and I hope one of you can answer my question. How come this code will produce the output "116"?

#include <iostream>

int main()
{
    std::cout << 0164 << std::endl;
    return 0;
}

The code has been compiled with MSVC++ 2010 and g++ under Mac OS X. "cout" can print '0' alone and '164' alone, but as soon '0' is the first digit in the number the output changes.


Solution

  • Because the 0 in front makes the number be interpreted as octal.

    0164 = 
     4 * 1 +
     6 * 8 + 
     1 * 64
     = 116
    

    Or, via binary:

     0164 =
       0   1   6   4 = 
     000 001 110 100 =
     1110100 = 
     116
    

    The same goes for hexadecimal numbers, you write them as 0x1FA for example.