I have just begun teaching myself C out of K.N King's C Programming: A Modern Approach (2ndEdn).
I'm enjoying it, but am hoping to post the odd question here for advice if appropriate because unfortunately I don't have a tutor and some bits raise more questions then they answer!
I'm doing a question on taking an integer entered and displaying it in octal. It says there is an easy way to do it, but that comes later in the book. I have come up with the following:
// Convert a number to octal
int n, n2, n3, n4, n5, n6;
printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);
n6 = n % 8;
n5 = (n / 8) % 8;
n4 = ((n / 8) / 8) % 8;
n3 = (((n / 8) / 8) / 8) % 8;
n2 = ((((n / 8) / 8) / 8) / 8) % 8;
printf("%d%d%d%d%d", n2, n3, n4, n5, n6);
It works OK, but I'm not good at math and was wondering if there is a more efficient way of doing this or have I done it the only way possible...
If anyone else has the book it's Q4 p.71.
Thanks for your time. Andrew
P.S I did look in the search engine but couldn't find anything that was doing it this 'slower' way!
Everyone is right in saying that there's a built-in way to do that with printf
. But what about doing it yourself?
The first thing that came to mind is that one octal digit is exactly three bits. Therefore you can do the conversion this way:
while n != 0
n
into d
and print d
n
3 bits to the leftThe code is trivial, but I 'm not providing it so you can do it yourself (you will need to be familiar with the bitwise and shift operators in order to do it).
The easy way is probably to use printf()
's %o
format specifier:
scanf("%d", &n);
printf("%o", n);
Others have posted the real, production code answer, and now I see from your comments that you haven't done loops yet. Perhaps your book is trying to teach you about recursion:
void print_oct(int n)
{
if (n != 0) {
print_oct(n / 8);
printf("%d", n % 8);
}
}
This works for n > 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With