Here's the c program to convert binary to octal:
#include <stdio.h>
int binaryToOctal(int binaryNumber) {
int octalNumber = 0, decimalNumber = 0, i = 0;
// Convert binary to decimal
while (binaryNumber != 0) {
int remainder = binaryNumber % 10;
decimalNumber += remainder * (1 << i);
binaryNumber /= 10;
i++;
}
// Convert decimal to octal
i = 1;
while (decimalNumber != 0) {
int remainder = decimalNumber % 8;
octalNumber += remainder * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
int main() {
int binaryNumber;
printf("Enter a binary number: ");
scanf("%d", &binaryNumber);
if (binaryNumber < 0) {
printf("Please enter a positive binary number.\n");
} else {
int octalNumber = binaryToOctal(binaryNumber);
printf("The octal equivalent is: %d\n", octalNumber);
}
return 0;
}
Explanation:
We include the necessary standard input-output header file
stdio.h
.In the
binaryToOctal
function, we convert the binary number to an octal number in two steps: binary to decimal, and then decimal to octal.In the
binaryToOctal
function, we initializeoctalNumber
anddecimalNumber
to 0, andi
to 0.octalNumber
will store the octal result, anddecimalNumber
will store the intermediate decimal representation of the binary number.i
is used as an exponent of 2 for binary to decimal conversion.We use a while loop to convert binary to decimal. We extract the least significant digit (LSB) of the binary number, multiply it by 2 to the power of
i
, and add it todecimalNumber
. We then shift the binary number right by one digit by dividing it by 10 and incrementi
.After converting the binary number to decimal, we initialize
i
as 1 and use a while loop to convert decimal to octal. We extract the remainder when dividing the decimal number by 8, multiply it byi
, and add it tooctalNumber
. We then divide the decimal number by 8 and multiplyi
by 10.In the
main
function, we take the user's input for the binary number.We check if the entered binary number is negative and prompt the user to enter a positive binary number if it's negative.
If the binary number is non-negative, we call the
binaryToOctal
function to convert it to octal and then print the result.Example:
Input:
Enter a binary number: 110101
Output:
The octal equivalent is: 55
In this example, the binary number
110101
is converted to its octal equivalent, which is55
.