Example 1: Program to Convert Binary to Octal
We first converted binary number to decimal. Then, the decimal number is converted to octal.
#include <stdio.h>
#include <math.h>
int convertBinarytoOctal(long long binaryNumber);
int main()
{
long long binaryNumber;
printf("Enter a binary number: ");
scanf("%lld", &binaryNumber);
printf("%lld in binary = %d in octal", binaryNumber, convertBinarytoOctal(binaryNumber));
return 0;
}
int convertBinarytoOctal(long long binaryNumber)
{
int octalNumber = 0, decimalNumber = 0, i = 0;
while(binaryNumber != 0)
{
decimalNumber += (binaryNumber%10) * pow(2,i);
++i;
binaryNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
Output
Enter a binary number: 101001
101001 in binary = 51 in octal
Example 2: Program to Convert Octal to Binary
We first converted octal number to decimal. Then, the decimal number is converted to binary.
#include <stdio.h>
#include <math.h>
long long convertOctalToBinary(int octalNumber);
int main()
{
int octalNumber;
printf("Enter an octal number: ");
scanf("%d", &octalNumber);
printf("%d in octal = %lld in binary", octalNumber, convertOctalToBinary(octalNumber));
return 0;
}
long long convertOctalToBinary(int octalNumber)
{
int decimalNumber = 0, i = 0;
long long binaryNumber = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
return binaryNumber;
}
Output
Enter an octal number: 67
67 in octal = 110111 in binary
No comments:
Post a Comment