In this tutorial, we will write a C program to convert a binary number into octal using a while loop. Before that, you must have knowledge of the following topics in C.
Binary number
The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.
Octal number
The octal numbers are the numbers with base 8 and use the digits 0 to 7. Example: 8 in decimal is represented as 10 in octal, 25 as 31, and so on.
Example:
Input: 101001
Output: 51
Let us go through a program for the Binary to Octal Conversion in C.
C Program to Convert Binary to Octal
Source Code: convert binary to octal using a function in C
#include <stdio.h>
#include <math.h>
int conversionFunc(int binaryNum)
{
int octalNum = 0, decNum = 0, i = 0;
while (binaryNum != 0)
{
decNum += (binaryNum % 10) *pow(2, i);
++i;
binaryNum /= 10;
}
i = 1;
while (decNum != 0)
{
octalNum += (decNum % 8) *i;
decNum = decNum / 8;
i *= 10;
}
return octalNum;
}
int main()
{
int binaryNum;
printf("Enter a binary number: ");
scanf("%d", &binaryNum);
printf("Octal Equivalent Value: %d", conversionFunc(binaryNum));
return 0;
}
Output:
Enter a binary number: 101001
Octal Equivalent Value: 51