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.
Advertise on this site. I promise you will like the rates :)
|Input the decimal value||The octal number is|
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.
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.
See also other number conversions: