Home »
C programs »
C number system conversion programs
C program to convert a binary number to an octal number
Here, we are going to learn how to convert a binary number to an octal number in C programming language?
Submitted by Nidhi, on July 03, 2021
Problem statement
Here, we will read a number in binary format (0s and 1s) from the user and convert it to an octal number, and print it on the console screen.
C program to convert a binary number to an octal number
The source code to convert a binary number to an octal number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C Program to convert a binary number to octal number
#include <stdio.h>
int main()
{
int binaryNumber = 0;
int octalNumber = 0;
int i = 1;
int rem = 0;
printf("Enter binary number: ");
scanf("%d", &binaryNumber);
while (binaryNumber != 0) {
rem = binaryNumber % 10;
octalNumber = octalNumber + rem * i;
i = i * 2;
binaryNumber = binaryNumber / 10;
}
printf("Octal Number: %o", octalNumber);
return 0;
}
Output
Enter binary number: 1011
Octal Number: 13
Explanation
Here, we created 4 integer variables binaryNumber, octalNumber, i, rem that are initialized with 0. Then we read a number in binary format (1s and 0s). Then we converted the number into a decimal number and printed the corresponding octal number using the "%o" format specifier on the console screen.
C Number System Conversion Programs »