You are reading this octal to decimal article for one of the following reasons:
|Input the octal number||The decimal value is|
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:
Result = 7 + 16 = 64 = 871278 = 8710
The source of the complete example is available as a direct download from here: octal-to-decimal.zip
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 ;-)
See also how to convert from: