Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to octal in C

Tags:

c

decimal

octal

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!

like image 480
aussie_aj Avatar asked Mar 19 '11 11:03

aussie_aj


3 Answers

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:

  • Loop while n != 0
  • Isolate the leftmost 3 bits of n into d and print d
  • Shift n 3 bits to the left

The 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).

like image 103
Jon Avatar answered Sep 22 '22 13:09

Jon


The easy way is probably to use printf()'s %o format specifier:

scanf("%d", &n);
printf("%o", n);
like image 20
Frédéric Hamidi Avatar answered Sep 25 '22 13:09

Frédéric Hamidi


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.

like image 35
fizzer Avatar answered Sep 26 '22 13:09

fizzer