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:
Example:
Result = 7 + 16 = 64 = 87
1278 = 8710The 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 ;-)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | int main(void) { char oct[23]; int length; unsigned long decimal; scanf("%22s", oct); length = strlen(oct); decimal = octToDecimal(oct, length); printf("%s in oct is %lu in decimal\n", oct, decimal); return 0; } unsigned long octToDecimal(char *oct, int length) { int i; unsigned long decimal = 0; unsigned long weight = 1; oct += length - 1; for(i = 0; i < length; ++i, --oct) { int coefficient = *oct - '0'; decimal += weight * coefficient; weight *= 8; } return decimal; } |
See also how to convert from: