CTechnotips: Binary to octal conversion in c language


Binary to octal conversion method:

Step1: Arrange the binary number in the group 3 from right side.

Step 2:  Replace the each group with following values:

Binary number
Octal values
000
0
001
1
010
2
011
3
100
4
101
5
110
6
111
7
Binary to octal chart  

Binary to octal conversion examples:

For example we want to convert binary number 1011010101001101 to octal.

Step 1: 001 011 010 101 001 101
Step 2:  1   3   2   5   1   5

So (1011010101001101)2 = (132515)8



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;
}

Sample output:

Enter any number any binary number: 1111111111111111111
1111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111
11111111
Equivalent octal value: 3777777777777777777777777777777
7777777777777777777777777777777777777777777777777777

0 comments:

Post a Comment