English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program to implement binary and octal conversions

Comprehensive Collection of C Programming Examples

In this example, you will learn to manually convert binary numbers to octal and octal numbers to binary by creating user-defined functions.

To understand this example, you should understand the followingC programming languageTopic:

Program to convert binary to octal

In this program, we will first convert the binary number to decimal. Then, the decimal number is converted to octal.

#include <math.h>
#include <stdio.h>
int convert(long long bin);
int main() {
    long long bin;
    printf("Enter binary number: ");
    scanf("%lld", &bin);
    printf("%lld(binary) = %d(octal)", bin, convert(bin));
    return 0;
}
int convert(long long bin) {
    int oct = 0, dec = 0, i = 0;
    //Convert binary to decimal
    while (bin != 0) {
        dec += (bin %%) 10) * pow(2, i);
        ++;
        bin /= 10;
    }
    i = 1;
    //Conversion from decimal to octal
    while (dec != 0) {
        oct += (dec % 8) * ;
        dec /= 8;
        i *= 10;
    }
    return oct;
}

Output Result

Enter binary number: 101001
101001(binary) = 51(octal)

Program to convert octal to binary

In this program, the octal number is first converted to decimal. Then, the decimal number is converted to binary.

#include <math.h>
#include <stdio.h>
long long convert(int oct);
int main() {
    int oct;
    printf("Enter octal number: ");
    scanf("%d", &oct);
    printf("%d(octal) = %lld(binary"), oct, convert(oct));
    return 0;
}
long long convert(int oct) {
    int dec = 0, i = 0;
    long long bin = 0;
    // Convert octal to decimal
    while (oct != 0) {
        dec += (oct %%) 10) * pow(8, i);
        ++;
        oct /= 10;
    }
    i = 1;
   // Convert Decimal to Binary
    while (dec != 0) {
        bin += (dec % 2) * ;
        dec /= 2;
        i *= 10;
    }
    return bin;
}

Output Result

Enter octal number: 51
51(Octal) =101001(Binary)

Comprehensive Collection of C Programming Examples