#include <stdio.h>
#include <math.h>
int main() {
long long binary, octal = 0;
int digits = 0;
printf("Enter a binary number: ");
scanf("%lld", &binary);
while (binary != 0) {
int digit = binary % 1000;
int octal_digit = 0;
// Convert the 3-digit binary number to an octal digit
for (int i = 0; i < 3; i++) {
octal_digit += (digit % 10) * pow(2, i);
digit /= 10;
}
octal += octal_digit * pow(10, digits);
digits++;
binary /= 1000;
}
printf("The octal equivalent is %lld\n", octal);
return 0;
}
Enter a binary number: 101024
The octal equivalent is 58
binary
number, octal to store the octal
equivalent, and digits to keep track of the number of digits
in the octal number.printf
and scanf
.while
loop to convert each 3-digit group of the binary number to an octal digit. The loop continues until the binary number becomes 0.%
. We then convert this 3-digit binary number to an octal digit by multiplying each binary digit with the corresponding power of 2 (2^0, 2^1, or 2^2) and adding the results. We add this octal digit to the octal
variable, multiplied by 10 raised to the current number of digits.binary
number by 1000 to remove the processed 3-digit group, and increment the digits
variable by 1 to move to the next position in the octal number.octal
variable as the octal equivalent using printf
.