To convert from decimal to octal, just use the online converter below. You will also learn how to do the calculation yourself. Finally, you will follow the implementation of the algorithm in C, to exercise your programming skills.
Input the decimal value | The octal number is | |
---|---|---|
If you are already familiar with the decimal to binary or decimal to hex conversion, this one will be very easy for you. It uses the same principle.
To convert from decimal to octal:
Note that this implementation is for learning purpose only. It shows you how to write a program that follows the above mentioned algorithm. C has a standard way for converting numbers from decimal to octal, using the itoa function.
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 30 31 32 33 34 35 | int main(void) { unsigned long decimal; char *octal; scanf("%lu", &decimal); octal = decimalToOctal(decimal); printf("%lu in dec equals %s in octal\n", decimal, octal); return 0; } char *decimalToOctal(unsigned long decimal) { char *octal = malloc(23); if(octal == NULL) exit(1); octal += 22; *octal-- = '\0'; if(decimal == 0) { *octal = '0'; } else { char remainder; while(decimal > 0) { remainder = (decimal % 8) + '0'; *octal-- = remainder; decimal = decimal / 8; } octal++; } return octal; } |
To implement the above algorithm, we need a string(char point) that will hold the remainders. We begin, by allocating the necessary space for the result: 23 bytes. The input data is at most 64 bits long. To hold that we need at most 22 octal digits and one null character to terminate the string.
We write the results in reversed order, so we won't need to reverse them later. To do that, we move the pointer to its end and insert the terminating symbol.
Then the actual conversion begins. In the while loop we divide the decimal input. The remainder of the division decimal % 8 is an integer from 0 to 7. To convert that remainder to its char representation we sum it with the character '0'. The result is the ASCII code of the digit. If you are not familiar with char arithmetic, you might want to check out this lesson:characters in C.
We save the remainder in the current position of the char pointer. Then we move the pointer one symbol to the left. We do these two operations with the single line:
*octal-- = remainder;
Then we divide the decimal number and close the loop. When we are done with the divisions the pointer is one symbol to the left of the result. We correct this ( octal++; ) and return the result.
The source code of the example is available on our GitHub.
.. or you can
download it from here: decimal-to-octal.zip
See also other number conversions: