Given a binary number as input, write a C program to convert it to its equivalent octal representation.
Example:
Input: 10100 Output: 24 Input: 11011 Output: 33
- Binary Number: A binary number is expressed in the base-2 numeral system, which uses only two symbols: 0 and 1.
- Octal Number: An octal number is expressed in the base-8 numeral system, which uses the digits from 0 to 7.
Step-by-step approach:
C program to convert a Binary Number to Octal Number.
//C code implementation of converting Binary to Octal #include <stdio.h> int main() { long long binary, decimal = 0; int power = 0; printf("Enter a binary number: "); scanf("%lld", &binary); // Convert binary to decimal while (binary != 0) { int digit = binary % 10; decimal += digit * (1 << power); power++; binary /= 10; } // Convert decimal to octal int octalNum[100], i = 0; while (decimal != 0) { octalNum[i] = decimal % 8; decimal /= 8; i++; } printf("Octal Equivalent: "); for (int j = i - 1; j >= 0; j--) { printf("%d", octalNum[j]); } return 0; }
Enter a binary number: 11010
Octal Equivalent: 32