The octal number system uses 8 digits(0..7) to represent the numbers.
It is rarely used today, but it is easy to convert to/from it. To
convert from octal to decimal, follow the general algorithm from
X-base to dec:
Start from the right-most octal digit. Its weight is 1, its value is
1 * the value of the digit. Save that value in the result.
Move one position to the left. This position has a weight 8 times the
previous. The value of this position is the product of its weight and
the value of the digit. Add the product to the previous result.
Repeat 2 until you go through all digits.
108 = ?10
The right-most position has a weight of 1. The digit there is 0. The
value of that position is 0 * 1 = 0
The next position to the left has a weight of 1 * 8. The digit in
this position is 1. The value of this position is 8 * 1 = 1. We add
the product 8 to the last result 0. 8 + 0 = 8
No more digits
108 = 810
1278 = ?10
weight=1, digit 7, value = 7
weight= 8 * 8=64, digit = 1, value = 64 * 1
weight= 1 * 8, digit 2, value = 8 * 2 = 16
= 7 + 16 = 64 = 87
1278 = 8710
Try to convert several numbers from octal to decimal by yourself. You can try on paper. Then check with the converter above if your result is correct.
In C, we don' t have a separate data type for octal numbers. For the purpose of this lesson, we will use a string (in other words a char array) to save the octal digits. Then we will convert them to a decimal number.
We want to be able to convert 64 bit numbers. The octal digits save up to 3 bits, so we will need at most 22 digits and one null symbol to terminate the string. We create a char array with 23 elements and read at most 22 symbols from the input.
At this moment we should perform validation of the data, but let's just focus on the conversion part.
We start to read the digits from right-to-left or in other words from the least significant towards the most significant. According to the algorithm above, we start from weight 1 for the least significant digit. Each position to the left has 8 times the weight of the previous.
Since we keep the digits in chars, we need to convert them to their corresponding int values, before we do the math. This conversion is done with the char arithmetic: *octal - '0'
Once we have the weight and the value of the digit, we multiply them and add to the result.
Besides the backward iteration, the implementation is pretty straight-forward ;-)