How To Convert Octal To Decimal In C?

Octal and decimal are two commonly used number systems in computing. Octal is a base-8 number system, which means it uses 8 digits (0-7) to represent numbers. Decimal, on the other hand, is a base-10 number system that uses 10 digits (0-9).

In C programming, there are several methods to convert an octal number to decimal including Using pow() function, strtol() function,Without using pow() function and Format Specifier.

Why is there a need to convert octal to decimal in c?

There are many reasons why you might need to convert an octal to decimal in c.

  1. Working with Binary Data: Many programming tasks require working with binary data in decimal form.Conversion of octal to decimal may be necessary when reading binary data from a file or network socket.
  2. Performing Arithmetic Operations: Two numbers represented in different numeral systems, such as octal and decimal, cannot undergo arithmetic operations directly.One of the numbers must be converted to the other numeral system first.Conversion of octal to decimal and vice versa may be necessary to perform arithmetic operations.
  3. Interfacing with Hardware: Some hardware devices, such as microcontrollers, use octal or other numeral systems to represent data.Conversion of octal to decimal may be necessary to interface with these devices correctly.

Four Methods for converting octal to decimal in C:

There are several ways to convert a octal to decimal in C:

  1. Using pow() function
  2. Using the strtol() function
  3. Without using pow() function
  4. Using Format Specifier

A thorough explanation of each strategy about how to convert octal to decimal in C:

1.Using pow() function to convert octal to decimal

This function can be used to convert an octal number to a decimal number by iterating over each digit of the octal number, multiplying it by 8 raised to the power of its position, and summing the results.

Sample Code:

#include <stdio.h>
#include <math.h>

int main() {
    int octalNum = 32; // Decimal number 26
    int decimalNum = 0;
    int i = 0;

    while (octalNum != 0) {
   	 int digit = octalNum % 10;
   	 decimalNum += digit * pow(8, i);
   	 i++;
   	 octalNum /= 10;
    }

    printf("Decimal number is %d\n",  decimalNum);
    return 0;
}

Output:

Decimal number is 26

Code Explanation:

  1. The program converts an octal number to its decimal equivalent.
  2. It uses the pow() function from the math library to raise 8 to the power of the position of each digit in the octal number.
  3. The last digit of the octal number is extracted using the % operator and multiplied with the calculated value to get its decimal equivalent.
  4. The calculated decimal equivalent is added to a variable that stores the overall decimal equivalent of the octal number.
  5. This process is repeated for each digit in the octal number until all digits have been converted.
  6. Once all digits have been converted, the decimal equivalent of the octal number is printed to the console using the printf() function.
  7. The program ends by returning 0.

2.  Using the strtol() function to change octal to decimal in C:

The strtol() function in C can also be used to convert an octal number to decimal. It takes three arguments: a string representing the octal number, a pointer to a char pointer that can be used to capture any remaining non-numeric characters in the input string, and the base of the input string (which is 8 for octal).

Sample Code:

#include <stdio.h>
#include <stdlib.h>

int main() {
	char octalStr[] = "32"; // decimal number 26
	long decimalNum = strtol(octalStr, NULL, 8);

	printf("Octal number %s in decimal is %ld\n", octalStr, decimalNum);
	return 0;
}

Output:

Octal number 32 in decimal is 26

Code Explanation:

  1. The program includes header files for input/output and standard library functions.
  2. The main function is defined with an integer return type.
  3. The octal number to be converted is stored as a string in the character array octalStr.
  4. The strtol() function is used to convert the octal string to its decimal equivalent.
  5. The decimal equivalent is stored in a long integer variable called decimalNum.
  6. The original octal string and its decimal equivalent are printed to the console using printf().
  7. The program ends by returning 0.

3. Change octal to decimal Without using pow() function :

This method involves extracting each digit of the octal number from right to left using a while loop. For each digit, the method multiplies the digit by the appropriate base (8 raised to a power) and adds it to a running total. The base value is then updated for the next digit. Once all digits have been processed, the running total represents the decimal equivalent of the octal number.

Sample Code:

#include <stdio.h>

int main() {
	int octal = 23; // an example octal number
	int decimal = 0;
	int base = 1;

	while (octal != 0) {
    	int rem = octal % 10;  // get the rightmost digit
    	octal /= 10;       	// remove the rightmost digit
    	decimal += rem * base; // add the digit to the decimal value
    	base *= 8;         	// update the base value
	}

	printf("decimal number is %d\n",  decimal);

	return 0;
}

Output:

decimal number is 19

Code Explanation:

  1. Initialize the octal variable with an example octal number.
  2. Initialize the decimal variable with 0.
  3. Initialize the base variable with 1.
  4. Extract each digit of the octal number from right to left using a while loop.
  5. In each iteration of the loop, extract the rightmost digit using the modulo operator % and divide the octal variable by 10 to get the remaining digits.
  6. Multiply the extracted digit with the current base value and add it to the decimal variable.
  7. Multiply the base value by 8 to get the base for the next digit.
  8. Repeat the loop until all digits have been extracted.
  9. Print the decimal value using the printf() function.

4. Convert octal to decimal using Format Specifier method:

To convert an octal number to a decimal number in C, you can use format specifiers in printf and scanf functions. Here are the format specifiers you can use:

  • %o: This format specifier is used to print an octal number in C.
  • %d or %i: These format specifiers are used to print a decimal number in C.

Sample Code:


#include <stdio.h>

int main()
{
    int num;
//take octal number as input
    scanf("%o", &num);
    // printing decimal number
    printf("decimal number is %d", num);
    return 0;
}

Output:

55
decimal number is 45

Code Explanation:

  1. The code begins by including the stdio.h header file, which contains functions for input and output in C.
  2. The main() function is defined, which is the entry point of the program.
  3. An integer variable octal is declared and initialized with the value 23, which is an example octal number.
  4. Another integer variable decimal is declared, which will hold the decimal equivalent of the octal number.
  5. The printf() function is used to print the value of octal in both octal and decimal formats using %o and %d format specifiers, respectively.
  6. The scanf() function is used to read an octal value from the user, which is stored in the variable octal.
  7. Finally, the printf() function is used again to print the new value of octal in both octal and decimal formats.

Best of the four methods:

There are several reasons why the strtol() function is often considered the best method for converting octal to decimal in C:

  1. Error checking: strtol() provides built-in error checking for invalid input. If the input string is not a valid octal number, the function will return an error code, allowing you to handle the error appropriately.
  2. Flexibility: strtol() allows you to convert not only octal numbers, but also binary and hexadecimal numbers. Additionally, you can specify the base of the input number, which can be useful for more complex scenarios.
  3. Efficiency: strtol() is a built-in library function, meaning it is optimized for performance and is likely to be more efficient than custom-written code.
  4. Ease of use: Once you understand how to use strtol(), it is a simple and straightforward method for converting octal to decimal, and can handle multiple numbers within a single string.

Overall, the strtol() function is a robust and reliable method for converting octal to decimal, and is particularly useful in more complex scenarios where error checking and flexibility are important.

Sample Problems for Converting object to decimal in C:

1. Sample Problem using pow() function :

Problem: Write a C program to convert the octal number “623” to its decimal equivalent using the pow() function

Solution:

  1. Initialize the octal variable with the octal number to convert.
  2. Initialize the decimal variable with the value 0.
  3. Initialize the i variable with the value 0.
  4. Use a while loop to extract each digit from the right to the left of the octal number.
  5. In each iteration of the loop, use the modulo operator % to extract the rightmost digit of the octal variable, and use integer division to obtain the remaining digits.
  6. Multiply the extracted digit by the result of the pow() function, which calculates 8 raised to the power of i, and add the result to the decimal variable.
  7. Increment the i variable by 1 to get the next power of 8 for the next digit.
  8. Continue the loop until all digits have been extracted from the octal variable.
  9. Use the printf() function to print the decimal value of the octal variable.

 Code:


#include <stdio.h>
#include <math.h>

int main() {
	int octal = 0623; // octal number 623
	int decimal = 0;
	int i = 0;
    
	while(octal != 0) {
    	int rem = octal % 10;
    	decimal += rem * pow(8, i);
    	++i;
    	octal /= 10;
	}
    
	printf("Octal number 623 in decimal is: %d\n", decimal);
    
	return 0;
}

Output:

Octal number 623 in decimal is: 403

2. Sample Problem for strtol() function

Problem:

Write a C program that takes an octal number as input from the user using the scanf() function, and then converts it to its decimal equivalent using the strtol() function. Finally, the program should output the decimal equivalent using the printf() function.

Solution:

  1. Declare a char array to store the input octal number as a string
  2. Declare a long int variable to store the converted octal number
  3. Declare an int variable to store the decimal equivalent
  4. Use the scanf() function to get input from the user, limiting the number of characters to 10 to avoid buffer overflow
  5. Use the strtol() function to convert the octal string to a long int with a base of 8
  6. Cast the long int to an int and store it in decimal_num
  7. Use printf() to output the original octal string and its decimal equivalent

 Code:

#include <stdio.h>
#include <stdlib.h>

int main() {
	char octal_str[11];
	long int octal_num;
	int decimal_num;

	// Prompt the user to enter an octal number
	printf("Enter an octal number: ");
	scanf("%10s", octal_str);

	// Convert the octal string to a long int using strtol()
	octal_num = strtol(octal_str, NULL, 8);

	// Convert the long int to an int and store it in decimal_num
	decimal_num = (int)octal_num;

	// Output the decimal equivalent using printf()
	printf("The decimal equivalent of %s is %d\n", octal_str, decimal_num);

	return 0;
}

Output:

Enter an octal number: 55
The decimal equivalent of 55 is 45

3. Sample Problem Without using pow() function :

Problem:

Write a C program to convert the octal number “763” to its decimal equivalent without using the pow() function.

Solution:

  1. Remember that in octal notation, each digit represents a power of 8.
  2. Start with a base value of 1 for the rightmost digit and then update the base value for each subsequent digit by multiplying it by 8.
  3. Use the modulo operator % to extract the rightmost digit of the octal number.
  4. Use integer division / to remove the rightmost digit of the octal number.
  5. Use a while loop to process all digits of the octal number.

 Code:

#include <stdio.h>

int main() {
	int octal = 763; // an example octal number
	int decimal = 0;
	int base = 1;

	while (octal != 0) {
    	int digit = octal % 10; // extract the rightmost digit
    	octal /= 10; // remove the rightmost digit
    	decimal += digit * base; // multiply the digit by the appropriate base and add it to the running total
    	base *= 8; // update the base for the next digit
	}

	printf("%d in decimal is %d in decimal\n", 763, decimal);
    
	return 0;
}

Output:

763 in decimal is 499 in decimal

4. Sample Problem Using Format Specifier:

Problem:

Write a C program to take an octal number as input from the user using the scanf() function and convert it to its decimal equivalent using format specifiers. Finally, the program should output the decimal equivalent using the printf() function.

Solution:

  1. Declare variables to hold the octal and decimal values, and a base variable to compute the decimal equivalent.
  2. Use the scanf() function to input the octal number in octal format (“%o”).
  3. Use a while loop to extract each digit of the octal number and compute the decimal equivalent.
  4. Inside the loop, extract the rightmost digit of the octal number using the modulo operator (%), and update the decimal equivalent using the appropriate base.
  5. Divide the octal number by 10 to get the next digit, and multiply the base by 8 for the next iteration.
  6. Use the printf() function to output the decimal equivalent using the “%d” format specifier.

 Code:

#include <stdio.h>

int main() {
	int octal, decimal = 0, base = 1, temp;

	printf("Enter an octal number: ");
	scanf("%o", &octal);

	temp = octal;

	while (temp != 0) {
    	decimal += (temp % 10) * base;
    	temp /= 10;
    	base *= 8;
	}

	printf("%o in octal is %d in decimal\n", octal, decimal);
    
	return 0;
}

Output:

Enter an octal number: 777
777 in octal is 329 in decimal

 Conclusion:

In this blog post, we learned how to convert  octal to decimal in C .Converting a octal value to a decimal can be achieved using several methods like Using pow() function, strtol() function,Without using pow() function and Format Specifier.However, after examining the advantages of each approach, it’s clear that strtol() function is the best option to use.

Also, the other methods can be useful in certain situations. When choosing a method, consider which one is the most appropriate for your use case.