C Program to Convert Binary to Octal and Hexadecimal

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

// Program for Binary to Octal
#include<stdio.h>
#include<conio.h>
int main()
{
    system("cls");
     int n,dn=0,r,b=1,binary,ar[50],i;
     printf("Enter a binary no(only o and 1 format)");
     scanf("%d",&n);  
     binary=n;  
     while(n!=0)
     {
        r=n%10; 
        dn=dn+r*b; 
        b=b*2;    
        n=n/10;  
     }
     printf("\n Binary Number: %d",binary);
     printf("\n Decimal Number: %d",dn);
     i=0;
     while(dn!=0)
     {
         r=dn%8;
         ar[i]=r;
         i++;
         dn=dn/8;
     }
     printf("\n Octal Number : ");
     i--;
     while(i>=0)
     {
          printf("%d",ar[i]);
          i--;
     }

    return 0;

}

Program 2

// Program for Binary to HexaDecimal
#include<stdio.h>
#include<conio.h>
int main()
{
    system("cls");
     int n,dn=0,r,b=1,binary,ar[50],i;
     printf("Enter a binary no(only o and 1 format)");
     scanf("%d",&n);  
     binary=n;  
     while(n!=0)
     {
        r=n%10; 
        dn=dn+r*b; 
        b=b*2;    
        n=n/10;  
     }
     printf("\n Binary Number: %d",binary);
     printf("\n Decimal Number: %d",dn);
     i=0;
     while(dn!=0)
     {
         r=dn%16;
         ar[i]=r;
         i++;
         dn=dn/16;
     }
     printf("\n Hexadecimal Number : ");
     i--;
     while(i>=0)
     {
        switch(ar[i])
        {
            case 10:printf("A");break;
            case 11:printf("B");break;
            case 12:printf("C");break;
            case 13:printf("D");break;
            case 14:printf("E");break;
            case 15:printf("f");break;
            default:printf("%d",ar[i]);
        }
        
          i--;
     }

    return 0;

}

Program 3

// Program for Binary to HexaDecimal
#include<stdio.h>
#include<conio.h>
int main()
{
    system("cls");
     int n,r,dec,ar[50],i;
     printf("Enter a Decimal Number");
     scanf("%d",&n);  
     dec=n;  
     i=0;
     while(n!=0)
     {
         r=n%2;
         ar[i]=r;
         i++;
        n=n/2;
     }
     printf("\n Binary Number : ");
     i--;
     while(i>=0)
     {
        printf("%d",ar[i]);
        i--;
     }   


    return 0;

}

 

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *