I'm trying to make a program that converts octal numbers into regular integers. My code looks like this.
#include <stdio.h>
int main(void) {
unsigned int c, num = 0, ct = 0;
printf("Please input a positive octal integer and end with pressing Enter:\n");
// Read the octal string, at most 10 characters.
while ((c = getchar()) != '\n' && ((c >= '0' && c <= '9') && ct++ < 11)) {
// Convert the input string to an value storing in int
num = num << 3 | (c - '0');
}
// If the input is not valid, output the error message.
if (c != '\n') {
printf("ERROR: the input should be an octal string containing 0-7, with length less than 11!\n");
} else { // Output the conversion table.
printf("i\t8^i\tdigit\tproduct\n");
for (int i = 0; i < ct; i++) {
printf("%u\t%u\t%u\t%u\n",
i, // Position i
1 << (3 * i), // Get 8 ** i
num >> (3 * i) & 7, // Get bit at position i
(1 << (3 * i)) * (num >> (3 & i) & 7)); // Multiply 8 ** i to the bit at position i
}
// Output the decimal value
printf("Decimal value: %d\n", num);
}
return 0;
}
The result should be this:
Please input a positive octal integer and end with pressing Enter:
7326
i 8^i digit product
0 1 6 6
1 8 2 16
2 64 3 192
3 512 7 3584
Decimal value: 3798
But instead it looks like this:
Please input a positive octal integer and end with pressing Enter:
7326
i 8^i digit product
0 1 6 6
1 8 2 24
2 64 3 320
3 512 7 1024
Decimal value: 3798
I believe the problem lies in line 32-33:
num >> (3 * i) & 7, // Get bit at position i
(1 << (3 * i)) * (num >> (3 & i) & 7)); // Multiply 8 ** i to the bit at position i
But I don't know how to solve the problem specifically.