Binary to octal conversion in c

C program c program to convert binary to octal

#include<stdio.h>
int main(){
   
    long int binaryNumber,octalNumber=0,j=1,remainder;

    printf("Enter any number any binary number: ");
    scanf("%ld",&binaryNumber);

    while(binaryNumber!=0){
         remainder=binaryNumber%10;
        octalNumber=octalNumber+remainder*j;
        j=j*2;
        binaryNumber=binaryNumber/10;
    }

    printf("Equivalent octal value: %lo",octalNumber);

    return 0;
}

Sample output:

Enter any number any binary number: 1101
Equivalent hexadecimal value: 15

 C code for how to convert large binary to octal

#include<stdio.h>
#define MAX 1000

int main(){
   
    char binaryNumber[MAX],octalNumber[MAX];
    long int i=0,j=0;

    printf("Enter any number any binary number: ");
    scanf("%s",binaryNumber);

    while(binaryNumber[i]){
      binaryNumber[i] = binaryNumber[i] -48;
      ++i;
    }

    --i;
    while(i-2>=0){
    octalNumber[j++] = binaryNumber[i-2] *4 +  binaryNumber[i-1] *2 + binaryNumber[i] ;
    i=i-3;
    }

    if(i ==1)
      octalNumber[j] = binaryNumber[i-1] *2 + binaryNumber[i] ;
    else if(i==0)
      octalNumber[j] =  binaryNumber[i] ;
    else
      --j;

    printf("Equivalent octal value: ");
    while(j>=0){
      printf("%d",octalNumber[j--]);
    }

    return 0;
}

No comments:

Post a Comment