Program for Binary to Octal Conversion in C
Binary to Octal Conversion
Converting a binary number to octal involves grouping binary digits into sets of three from right to left and converting each set to its octal equivalent.
We will explore three methods to perform this conversion using C programming.
Method 1: Using Built-in Function
We first convert the binary number to decimal and then use C's built-in function to convert it to octal.
#include <stdio.h> #include <stdlib.h> int main() { char binary[32]; printf("Enter a binary number: "); scanf("%s", binary); int decimal = strtol(binary, NULL, 2); printf("Octal: %o\n", decimal); return 0; }
Example Output:
Enter a binary number: 101101 Octal: 55
Method 2: Using Division by 8
We convert binary to decimal and then repeatedly divide the decimal number by 8 to get the octal equivalent.
#include <stdio.h> #include <math.h> int binaryToDecimal(int binary) { int decimal = 0, base = 1; while (binary > 0) { decimal += (binary % 10) * base; binary /= 10; base *= 2; } return decimal; } void decimalToOctal(int decimal) { int octal[20], i = 0; while (decimal > 0) { octal[i++] = decimal % 8; decimal /= 8; } printf("Octal: "); for (int j = i - 1; j >= 0; j--) { printf("%d", octal[j]); } printf("\n"); } int main() { int binary; printf("Enter a binary number: "); scanf("%d", &binary); decimalToOctal(binaryToDecimal(binary)); return 0; }
Example Output:
Enter a binary number: 111001 Octal: 71
Method 3: Using Recursion
We use recursion to first convert binary to decimal and then recursively convert decimal to octal.
#include <stdio.h> int binaryToDecimalRecursive(int binary) { if (binary == 0) return 0; return (binary % 10) + 2 * binaryToDecimalRecursive(binary / 10); } void decimalToOctalRecursive(int decimal) { if (decimal == 0) return; decimalToOctalRecursive(decimal / 8); printf("%d", decimal % 8); } int main() { int binary; printf("Enter a binary number: "); scanf("%d", &binary); int decimal = binaryToDecimalRecursive(binary); printf("Octal: "); if (decimal == 0) printf("0"); else decimalToOctalRecursive(decimal); printf("\n"); return 0; }
Example Output:
Enter a binary number: 100110 Octal: 46