Write a C program to input Octal number from user and convert to Binary number system. How to convert from Octal number system to Binary number system in C. Logic to convert octal to binary number system in C programming.
Example
Input
Input octal number: 172
Output
Binary of 172: 01111010
Required knowledge
Basic C programming, While loop, Array
Octal number system
Octal number system is a base 8 number system. It uses 8 symbols to represent all its numbers i.e. 01234567
Binary number system
Binary number system is a base 2 number system. It uses only two symbols i.e. 0 and 1 to represent all numbers.
Logic to convert octal to binary number system
I have divided the octal to binary conversion in three steps.
- Extract last digit from octal number.
- Find binary equivalent of octal digit found above.
- Combine all converted binary together.
Octal to Binary conversion table
Decimal | Octal | Binary |
---|---|---|
0 | 0 | 000 |
1 | 1 | 001 |
2 | 2 | 010 |
3 | 3 | 011 |
4 | 4 | 100 |
5 | 5 | 101 |
6 | 6 | 110 |
7 | 7 | 111 |
Algorithm to convert octal to binary
Algorithm Conversion from Octal to Binary begin: read(octal); OCTALVALUES[] ← 0, 1, 10, 11, 100, 101, 110, 111; binary ← 0; rem ← 0; place ← 1; While(octal > 0) begin: rem ← octal % 10; binary ← (OCTALVALUES[rem] * place) + binary; octal ← octal / 10; place ← place * 1000; end; write('Binary =' binary); end;
Program to convert octal to binary number system
/**
* C program to convert Octal number system to Binary number system
*/
#include <stdio.h>
int main()
{
int OCTALVALUES[] = {0, 1, 10, 11, 100, 101, 110, 111};
long long octal, tempOctal, binary, place;
int rem;
/* Input Octal number from user */
printf("Enter any Octal number: ");
scanf("%lld", &octal);
tempOctal = octal;
binary = 0;
place = 1;
/* Convert octal to binary */
while(tempOctal > 0)
{
/* Extract the last digit of octal */
rem = tempOctal % 10;
/*
* Get the binary equivalent of octal digit
* add it to the binary variable
*/
binary = (OCTALVALUES[rem] * place) + binary;
/* Remove the last octal digit */
tempOctal /= 10;
/* Increase the place value */
place *= 1000;
}
printf("Octal number = %lld\n", octal);
printf("Binary number = %lld", binary);
return 0;
}
Output
Enter any Octal number: 1720 Octal number = 1720 Binary number = 1111010000
Happy coding 😉
Recommended posts
- Loop programming exercises and solutions in C.
- C program to convert Binary to Octal number system.
- C program to convert Octal to Decimal number system.
- C program to convert Octal to Hexadecimal number system.
- C program to convert Binary to Hexadecimal number system.
- C program to convert Decimal to Binary number system.