How to convert an array of integer to an octal number?

143 views Asked by At

I have an array like this: int arr[8] = {6, 4, 1, 6, 1, 1, 5, 6}. How to convert this array to an octal number 64161156. I use this code but its result is 364602604, 364602604 is decimal number 64161156 represented as octal.

#include <stdio.h>

int main() {
    int a[8] = {6, 4, 1, 6, 1, 1, 5, 6};
    int octal = 0;
    for(int i = 0; i < 8; i++)
        octal = octal * 10 + a[i];

    printf("%o\n", octal);

    return 0;
}
1

There are 1 answers

1
André Caldas On

A good idea is to organize the mathematical part before jump into programing.

The idea of what you want to do is:

result = a[7] + 8*a[6] + 8*8*a[5] + ... + 8*8*8*8*8*8*8*a[0].

(sorry, I could not figure out how to write mathematics here at SO)

What your code does is:

result = a[7] + 10*a[6] + 10*10*a[5] + ... + 10*10*10*10*10*10*10*a[0].

As @Weather Vane pointed out, internally the int octal is just a number. When you print it, it is print in whatever system you instruct the "print method" to do. So, your code is calculating in decimal and printing in octal.