In this article, we are going to learn how to convert a binary number to an Octal number. Here we are going to learn about two numbers one is binary and another is octal. Binary numbers are base 2 numbers and represented in 0s and 1s. Octal numbers are base 8 numbers and are represented in numbers from 0 to 7.
The binary to octal equivalent number table is given below. We are going to use this table in our program to convert the number.
Binary Number | Octal Number |
000 | 0 |
001 | 1 |
010 | 2 |
011 | 3 |
100 | 4 |
101 | 5 |
110 | 6 |
111 | 7 |
C program to convert binary to octal number
In this example, Write a C program to input binary numbers from users and convert them to the octal number system. We are going to take the input from the user in the form of a binary number. Then we will start from the right side of this binary number and will collect 3-3 bits to find their octal equivalent. We will continue doing this until we process all the bits in the binary number.
#include <stdio.h>
int main()
{
int octTable[] = {0, 1, 10, 11, 100, 101, 110, 111};
long long binNum;
long long octalNum;
long long temp;
int ThreeDigitEquivalent;
int index;
octalNum = 0;
index= 1;
printf("Please enter 8 bit binary number: ");
scanf("%lld", &binNum);
temp = binNum;
while(temp != 0)
{
ThreeDigitEquivalent = temp % 1000;
for(int i=0; i<8; i++)
{
if(octTable[i] == ThreeDigitEquivalent)
{
octalNum = (i * index) + octalNum;
break;
}
}
temp /= 1000;
index *= 10;
}
printf("Octal Equivalent to Binary number = %lld is = %lld \n", binNum,octalNum);
return 0;
}
Output
Please enter 8 bit binary number: 10101010
Octal Equivalent to Binary number = 10101010 is = 252