Slider

C Program to Convert Binary to Octal.

Given a binary number as input, write a C program to convert it to its equivalent octal representation. C program to convert a Binary Number to Octal

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

Before moving to the code section, let us learn about Binary and Octal numbers:
  • 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:

Step 1: Obtain the binary number as input.
Step 2: Convert the binary number to its decimal equivalent by iterating through each digit and multiplying it by 2 raised to a power.
Step 3: Convert the decimal number to its octal representation by dividing it by 8 repeatedly and storing the remainder.
Step 4: Print the resulting octal representation of the binary number.

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;
}
Output:
Enter a binary number: 11010
Octal Equivalent: 32

Time Complexity: The time taken to convert from binary to decimal is O(log₂ N) and the time taken to convert decimal to octal is O(log₂ N) so the overall time complexity is O(log₂ N + log₈ N).

Space Complexity: The space complexity of the code is O(log N) because we need to store the decimal equivalent of the binary number, and the number of digits in the decimal number is log N.
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson
Table of Contents