- How octal-to-decimal conversion is the same pattern as binary-to-decimal, with a different multiplier
- Why the place value multiplies by 8 (not 2 or 10) each iteration
- How octal digits are always 0-7 β and why any digit of 8 or 9 makes the input invalid
- How
n % 10works here just as it did for binary β because octal digits happen to be valid decimal digits - How the same skeleton handles hex conversion once you switch to string input
Same Idea, Different Multiplier
If you've done the binary-to-decimal program from assignment 14, this one will feel like a small variation. The structure is identical: read a number, loop over its digits, multiply each digit by the current place value, add it to an accumulator, and double the place value each iteration. The only change is the multiplier.
For binary, the place value doubles (multiplied by 2 each iteration): 1, 2, 4, 8, 16, 32, β¦ For octal, the place value multiplies by 8: 1, 8, 64, 512, 4096, 32768, β¦ For decimal (base 10), the place value would multiply by 10: 1, 10, 100, 1000, β¦ That's what makes base-10 so natural to us β we've memorised the multipliers. For octal, the multipliers grow faster, so octal numbers are shorter but their decimal equivalents grow quickly.
A quick intuition: octal 777 = 7Γ64 + 7Γ8 + 7Γ1 = 448 + 56 + 7 = 511. So the "largest three-digit octal number" is 511 in decimal, not 999. Octal representation is compact but not nearly as compact as it looks at first glance. In fact, octal was historically used in computing as a shorthand for binary β three octal digits pack exactly one byte's worth of bits (0-511), and every octal digit corresponds to exactly three binary digits (000-111). That correspondence is why octal was popular in the era of 12-bit and 36-bit machines.
π‘ In one line: for each octal digit d (right to left), add d Γ place to a running total, then multiply place by 8. Start at place = 1.
Base 8 Place Values
The algorithm differs from binary-to-decimal in exactly one line: place *= 8 instead of place *= 2. Everything else is identical. That's the point of a well-designed pattern β the specifics (which base) live in one place, and the skeleton stays stable.
- Read the octal number as an integer. Validate non-negativity.
- Initialise
decimal = 0andplace = 1. - Loop while
n > 0:- Extract the last digit:
digit = n % 10. - Validate:
digitmust be 0-7. Octal has no digit 8 or 9. - Add
digit Γ placetodecimal. - Multiply the place value:
place *= 8. - Remove the last digit:
n /= 10.
- Extract the last digit:
- Print
decimal.
The validation step is new compared to binary β not because octal digits are harder to check, but because octal has more valid digits (0 through 7), so there's a wider range to accept and reject. If the user enters 1089, that's not octal (8 and 9 aren't valid octal digits), and the program should say so clearly rather than computing a nonsense value.
| Octal | Calculation | Decimal | Note |
|---|---|---|---|
| 0 | 0 | 0 | Zero is zero in both bases |
| 7 | 7Γ1 | 7 | Single digit β max is 7 |
| 10 | 1Γ8 + 0Γ1 | 8 | First two-digit octal |
| 17 | 1Γ8 + 7Γ1 | 15 | Notice 17 in octal is 15 in decimal |
| 100 | 1Γ64 | 64 | First three-digit octal |
| 745 | 7Γ64 + 4Γ8 + 5Γ1 | 485 | Worked example |
| 777 | 7Γ64 + 7Γ8 + 7Γ1 | 511 | Largest three-digit octal |
The row for octal 17 is worth pausing on. In decimal, 17 is seventeen. In octal, 17 is fifteen (1Γ8 + 7). Same digits, different value β because the multiplier for the second position is 8, not 10. This is the kind of subtlety that catches beginners: they see "17" and assume the value is 17, but the program computes 15. Being explicit about the base at every step is the way to avoid confusion.
Complete C Program
Program: octal to decimal using a for loop
#include <stdio.h>
int main(void) {
long long n;
printf("Enter an octal number (digits 0-7 only): ");
if (scanf("%lld", &n) != 1 || n < 0) {
printf("Invalid input. Please enter a non-negative octal number.\n");
return 1;
}
long long original = n; /* keep for display */
long long decimal = 0;
long long place = 1;
/* The for loop's three parts: no initializer (n already set),
condition n > 0, update n /= 10 */
for (; n > 0; n /= 10) {
int digit = n % 10;
if (digit < 0 || digit > 7) {
printf("Invalid octal digit %d β octal digits are 0-7 only.\n", digit);
return 1;
}
decimal += digit * place;
place *= 8;
}
printf("Octal %lld = Decimal %lld\n", original, decimal);
return 0;
}
And here's the same logic using strtoll with base 8, which is what production code typically uses:
Alternative: use strtoll with base 8
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char input[64];
printf("Enter an octal number: ");
if (scanf("%63s", input) != 1) {
printf("Invalid input.\n");
return 1;
}
char *end;
long long decimal = strtoll(input, &end, 8);
if (*end != '\0') {
printf("Invalid octal number β %s contains non-octal digits.\n", input);
return 1;
}
printf("Octal %s = Decimal %lld\n", input, decimal);
return 0;
}
Same trade-off as in the binary program β the manual loop is instructive, the library version is shorter and safer. Both compute the same result. Use whichever fits the context: manual for the assignment, strtoll when writing real code that needs to convert user-supplied numbers.
Program Output
Enter an octal number (digits 0-7 only): 745
Octal 745 = Decimal 485
A few more to try. Input 17 gives 15 β remember, octal 17 is 1Γ8 + 7 = 15, not 17. Input 100 gives 64. Input 777 gives 511. Input 0 gives 0. Input 7 gives 7. Input 1089 gives an error message because 8 and 9 aren't valid octal digits. Input β17 gives an error because the input is negative.
Step-by-Step Explanation
Let's trace 745 through the loop, then look at the differences from binary conversion.
1. Reading and validating input
The initial scanf reads the number, and the check n < 0 rejects negatives (there's no standard way to write a negative octal number in this format). The individual-digit validation happens inside the loop, which lets us report the specific invalid digit.
2. Saving the original value
The loop destroys n. Saving original = n before the loop lets the final message print "Octal 745 = Decimal 485" rather than "Octal 0 = Decimal 485".
3. The main loop for 745
Trace:
- Start:
n = 745,decimal = 0,place = 1 - Iteration 1:
digit = 5,decimal += 5Γ1 = 5,place = 8,n = 74 - Iteration 2:
digit = 4,decimal += 4Γ8 = 32(total 37),place = 64,n = 7 - Iteration 3:
digit = 7,decimal += 7Γ64 = 448(total 485),place = 512,n = 0 - Loop exits β final
decimal = 485
Check: 7Γ64 + 4Γ8 + 5Γ1 = 448 + 32 + 5 = 485. Matches.
4. Why the multiplier is 8, not 2 or 10
Each position in an octal number represents a power of 8. The rightmost position is 8β° = 1, the next is 8ΒΉ = 8, the next is 8Β² = 64, and so on. So to convert digit-by-digit, you multiply each digit by the appropriate power of 8. The place variable tracks this power, starting at 1 and multiplying by 8 each iteration. Writing place *= 2 (like the binary program) would give a wrong answer; place *= 8 is the correct multiplier for octal.
5. Why octal digits are 0-7, not 0-9
In base-8 notation, there are exactly 8 symbols used: 0, 1, 2, 3, 4, 5, 6, 7. The digit 8 doesn't exist β it's represented as "10" in octal. Similarly, 9 is "11" in octal. So an "octal" input like 1089 is nonsensical β it uses digits that don't exist in base 8. The validation catches this and tells the user rather than silently producing garbage.
There's an interesting history here: octal was popular in computing because each octal digit corresponds to exactly three binary digits (bits). One byte (8 bits) is conventionally split as 3-3-2 or two octal digits plus a remainder. On old 12-bit and 36-bit architectures, octal was the natural display format. Modern systems prefer hexadecimal because each hex digit corresponds to exactly four binary digits, which fits bytes more neatly (two hex digits = one byte). But octal still shows up in file permissions on Unix systems β the famous chmod 755 is an octal number, meaning rwxr-xr-x.
6. Why n % 10 extracts "octal digits" here
Same reasoning as in the binary program β the coincidence works because octal digits are a subset of decimal digits. The user typed "745" as a decimal number (seven hundred forty-five in the C compiler's view). 745 % 10 = 5, 745 / 10 = 74. The loop extracts the decimal digits 5, 4, 7 in that order and treats them as octal digits. Because octal digits are valid decimal digits (0-7), the arithmetic works out. If octal had required a symbol like "A" for ten (which it doesn't, but hexadecimal does for A-F), this approach would break β which is exactly why the hexadecimal program (assignment 18) uses string input instead.
7. Overflow considerations
Both n and decimal use long long. A 12-digit octal number like 777777777777 has value 7Γ(8^11 + 8^10 + ... + 1) = 7Γ(8^12 β 1)/7 = 8^12 β 1 = 68,719,476,735, which fits comfortably in long long (max ~9.2 quintillion). For much larger octal numbers, you'd need a big-number library. For the assignment, 12-15 digits is more than sufficient.
π― Remember this: octal is just base 8. Each digit contributes digit Γ place to the decimal value, where place starts at 1 and multiplies by 8 each iteration (right to left). Validate that digits are 0-7. If you've done the binary program, the only change is place *= 8 instead of place *= 2.
Frequently Asked Questions
1. Why does the program treat octal 17 as decimal 15?
Because 17 in base 8 means 1Γ8 + 7Γ1 = 15 in base 10. The digits look familiar but the position weights are different. This is the most common source of confusion in base conversion β the symbols are the same, but the meaning depends on which base they're interpreted in. Octal 17 is not the same value as decimal 17. The program's job is to translate between the two interpretations.
2. What happens if the input has an 8 or 9 in it?
The program reports an error and stops. In octal, only 0-7 are valid digits β an "8" or "9" is meaningless because it doesn't correspond to any single octal digit. The validation if (digit < 0 || digit > 7) catches this. Without the check, the program would compute something (treating "8" as a value of 8Γplace, which overflows the digit's intended range) β a nonsensical answer presented as if valid. The error message is the honest response.
3. Could I convert to hex using the same loop?
Almost β but there's a wrinkle. In hexadecimal, digits go from 0 to 15, and for values 10-15 we use letters A-F. Those letters aren't decimal digits, so the n % 10 extraction fails (the user can't type "A" as part of an integer literal). You'd need to read the input as a string and process characters, converting 'A'-'F' to their numeric values 10-15. The skeleton β extract digit, multiply by place, add to total, multiply place by 16 β is the same, but the digit extraction step needs a string-level approach. Assignment 18 covers this case in detail.
4. Is octal still used today?
Yes, mostly in one specific place: Unix file permissions. The chmod command takes octal numbers like 755 (meaning rwxr-xr-x) or 644 (rw-r--r--). Each octal digit encodes the read/write/execute permissions for one class of user (owner, group, others), so a three-digit octal number describes the entire permission scheme compactly. Beyond that, octal is largely historical β most of the C language's early use of octal (like the 0 prefix for octal literals in C) is a legacy of the 1970s computing landscape.
5. Why use long long instead of int?
Octal numbers get large quickly. The largest 10-digit octal number is 7Γ8βΉ + 7Γ8βΈ + ... = 8ΒΉβ° β 1 = 1,073,741,823 β close to INT_MAX. So a 10-digit octal input can overflow int if it's large enough. Using long long for both n and decimal avoids that concern β a 19-digit octal number fits comfortably. And an octal number of 12+ digits, while larger than what int can hold, is still well within long long's range.
6. How would I convert in the other direction (decimal to octal)?
Different algorithm: instead of extracting and multiplying, you divide repeatedly and record remainders. while (n > 0) { digit = n % 8; print digit; n /= 8; } β but the digits come out in reverse order, so you either print them in reverse (via an array or recursion) or store them for later. Assignment 16 covers this exact conversion. It's the mirror image of this program: here we're extracting and multiplying, there we'll be dividing and collecting.
π‘ Tip: After this program, compare it side-by-side with assignment 14 (binary to decimal). The only differences are (a) place *= 8 instead of place *= 2, and (b) the digit validation range is 0-7 instead of 0-1. Everything else is identical. That's the whole idea of a well-designed pattern β the base is a parameter, and the rest of the code doesn't care. Once you see that, you can write base-N conversion for any N between 2 and 10 (or beyond, with string input) in a couple of minutes.