Search code examples
c++octal

How to work with Base 8 (Octal) numbers?


In C++, an octal number is defined by preceeding it with a 0, example:

01 = 1
010 = 8
014 = 12

So I was experimenting how working with Base 8 in c++ works, and tried adding to it with a loop, like so:

int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
    base8Number += i;
    cout << base8Number << '\n';
}

And apparently, C++ doesn't like working with octal numbers, the output I got is as follows:

1
3
6
10
15
21
28
36

The most obvious reason I know it's not working in Base 8, is the 28 output as a result, since the 8 number isn't used in Base 8.

So, my question: Can you work with Base 8 in c++, or is it just meant to be used as a constant, and if you can work with Base 8 in c++, how do you do it?


Solution

  • So first, let's remember that when we print numbers the way you're doing, they will be shown in decimal.

    Now, let's rewrite your code without octal:

    int base10Number = 0;
    for (int i = 1; i < 9; i+=1)
    {
        base10Number += i;
        cout << base10Number << '\n';
    }
    

    So let's now look at what your code is actually doing:

    cout << 1             << "\n"; // 1
    cout << 1 + 2         << "\n"; // 3
    cout << 1 + 2 + 3     << "\n"; // 6
    cout << 1 + 2 + 3 + 4 << "\n"; // 10
    ....
    

    Which is what you're seeing. So no, there is no problem with how octal works in c++.

    If you'd like you can use std::oct to tell std::cout to use octal printing. For example:

    int main() {
        std::cout << std::oct << 25 << "\n"; // Outputs: 31
    }