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.
Do you learn better from video?
Learn faster with deeper understanding! The "Computer programming for beginners" course is the perfect place to begin with programming.
Divide the decimal number by 8. Save the result and the remainder.
Repeat 1, but this time, divide the result from the last calculation. Once again, save the result and the remainder. Repeat until the result reaches 0.
Take the remainders in reversed order. Those remainders form the representation of the number in octal number system.
Here is an example with dec to octal:
1610 = ? (oct)
1: 16 / 8 = 2 and remainder 0
2: Repeat 1, using the previous result:
2 / 8 = 0 and remainder 2. We reached 0, so we continue with 3
3: The remainders of the division are 0 and 2. And reversed: 20.
1610 = 208
One more example:
10010 = ?(oct)
100 / 8 = 12; rem 4
12 / 8 = 1; rem 4
1 / 8 = 0; rem 1
The remainders are 441. Their reversed order is 144. So:
10010 = 1448
To exercise what you just read, convert several numbers in the range 10-200. When you are ready, test your result with the converter above.
Implementing the algorithm with C
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.
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.
the actual conversion begins. In the while loop we divide the decimal
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 arithmetics, you
might want to check out this lesson: characters in C.
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:
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.