In computer science, there are various ways to represent numbers. In addition to the binary and decimal systems we discussed earlier, the octal system is also a common numeral system. The octal system is base 8, using the digits 0 to 7 to represent all numbers. Although octal is not as widely used in daily life as decimal and binary, it still plays an important role in certain specific fields (such as file permission representation and some embedded system programming). This article will explore in detail how to implement the conversion between octal and decimal in C language, along with complete code examples.
1. Basics of Octal and Decimal
1.1 Octal
The octal system is a base 8 numeral system that uses the digits 0 to 7 to represent all numbers. In octal, the weight of each digit is the power of 8 corresponding to the position of that digit, counted from right to left as 8^0, 8^1, 8^2, … For example, the octal number 123
(note that this 123
is not the decimal 123, but the octal number) represents the decimal value of 1*8^2 + 2*8^1 + 3*8^0 = 64 + 16 + 3 = 83
.
1.2 Decimal
The decimal system is the numeral system we use in daily life, which is base 10 and uses the digits 0 to 9 to represent all numbers. In decimal, the weight of each digit is the power of 10 corresponding to the position of that digit, counted from right to left as 10^0, 10^1, 10^2, …
2. Converting Octal to Decimal
The process of converting an octal number to a decimal number is similar to converting binary to decimal, but here we use powers of 8 instead of powers of 2. For any given octal number, we simply multiply each digit by the corresponding power of 8 (from right to left, with increasing powers) and then sum all the results to obtain the corresponding decimal number.
2.1 Example Code
Below is a C program that converts a user-input octal string to a decimal integer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// Function declaration
int octalToDecimal(const char* octal);
int main() {
char octal[12]; // Assume the octal number does not exceed 11 digits (the maximum octal number 77777777777 is close to 2^33 in decimal, exceeding the int range, but this is just for example)
printf("Please enter an octal number (up to 11 digits): ");
scanf("%11s", octal);
// Check if the input consists only of digits between 0-7
for (int i = 0; octal[i] != '\0'; i++) {
if (octal[i] < '0' || octal[i] > '7') {
printf("Input error, it can only contain digits between 0-7!\n");
return 1;
}
}
int decimal = octalToDecimal(octal);
printf("The corresponding decimal number is: %d\n", decimal);
return 0;
}
// Function to convert octal to decimal
int octalToDecimal(const char* octal) {
int decimal = 0;
int length = strlen(octal);
for (int i = 0; i < length; i++) {
// Traverse from right to left, multiplying each digit by the corresponding power of 8
decimal += (octal[i] - '0') * (1 << (3 * (length - 1 - i))); // Use bitwise shift to quickly calculate powers of 8 (since 8 = 2^3)
}
return decimal;
}
Note: The 1 << (3 * (length - 1 - i))
part in the above code is used to calculate powers of 8, which is achieved through bitwise shifting since 8 = 2^3
. However, this method may lead to integer overflow when the octal number is long (since it uses int
type). In practical applications, if large numbers need to be considered, more advanced data types (such as long long
) or special libraries for handling large integers may be required.
For simplicity in this example, we assume that the input octal number will not exceed the representation range of int
.
2.2 Code Explanation
-
• The
octalToDecimal
function takes a pointer to a character array (octal string) as a parameter and returns the corresponding decimal integer. -
• The
strlen
function is used to get the length of the octal string. -
• A loop traverses each digit of the octal string from right to left.
-
• In the loop, the current character (‘0’-‘7’) is converted to the corresponding integer value (0-7), then multiplied by the corresponding power of 8 (achieved through bitwise shifting).
-
• Each calculated result is accumulated into the
decimal
variable. -
• Finally, the calculated decimal number is returned.
3. Converting Decimal to Octal
Converting a decimal number to an octal number is slightly more complex because we need to continuously divide the decimal number by 8 and record the remainder of each division until the quotient is 0. The sequence of these remainders (which may need to be padded with zeros to form a fixed-length string) constitutes the corresponding octal number.
3.1 Example Code
Below is a C program that converts a user-input decimal integer to an octal string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function declaration
void decimalToOctal(int decimal, char* octal);
int main() {
int decimal;
printf("Please enter a decimal number: ");
scanf("%d", &decimal);
// Assume the octal number does not exceed 32 bits (in actual use, this may need to be adjusted as needed)
char octal[33];
memset(octal, '0', 32); // Initialize the string with 32 '0's
octal[32] = '\0'; // Ensure the string ends with '\0'
int index = 31; // Start filling from the end of the string for later reversal
decimalToOctal(decimal, octal);
// Reverse the string (since it is filled from low to high)
int length = strlen(octal);
while (octal[length - 1] == '0') {
length--; // Remove leading zeros
}
for (int i = 0; i < length / 2; i++) {
char temp = octal[i];
octal[i] = octal[length - 1 - i];
octal[length - 1 - i] = temp;
}
// If the entire string is '0', only output one '0'
if (length == 0) {
printf("0\n");
} else {
octal[length] = '\0'; // Reset the string terminator
printf("The corresponding octal number is: %s\n", octal);
}
return 0;
}
// Function to convert decimal to octal
void decimalToOctal(int decimal, char* octal) {
int index = 31; // Initial index set to 31, filling from the end of the string
while (decimal > 0) {
octal[index--] = (decimal % 8) + '0'; // Get the remainder and convert to character, then fill into the string
decimal /= 8; // Update the decimal number to the quotient
}
// If the decimal number is 0, directly fill '0' (but this function will not reach here because the 0 case is already handled in the main function)
}
3.2 Code Explanation
-
• The
decimalToOctal
function takes a decimal integer and a pointer to a character array as parameters. This character array is used to store the converted octal string. -
• A loop continuously divides the decimal number by 8 and fills the corresponding position in the character array with the remainder (converted to characters ‘0’-‘7’). Note that it fills from the end of the string to facilitate later reversal.
-
• In the
main
function, since we fill the octal string from low to high, we need to reverse it before outputting and remove any leading zeros. -
• If the input decimal number is 0, it is directly output as ‘0’ in the
main
function, because thedecimalToOctal
function will not handle this case (it assumes the input decimal number is greater than 0).
Through the detailed explanation and code examples in this article, you should have mastered the method of implementing conversion between octal and decimal in C language. The conversion between octal and decimal is a fundamental skill in computer programming, which not only helps us understand the internal data representation of computers but also lays a solid foundation for our subsequent learning of more advanced programming techniques and algorithms. I hope this article can be helpful to you!