Decimal to octal in C

aussie_aj picture aussie_aj · Mar 19, 2011 · Viewed 16.9k times · Source

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!

Answer

Jon picture Jon · Mar 19, 2011

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