# C Program to Convert Binary to Octal

#include <stdio.h>
#include <math.h>
int binary_octal(int n);
int octal_binary(int n);
int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'o' to convert binary to octal.\n");
printf("2. Enter alphabet 'b' to convert octal to binary.\n");
scanf("%c",&c);
if ( c=='o' || c=='O')
{
printf("Enter a binary number: ");
scanf("%d",&n);
printf("%d in binary = %d in octal", n, binary_octal(n));
}
if ( c=='b' || c=='B')
{
printf("Enter a octal number: ");
scanf("%d",&n);
printf("%d in octal = %d in binary",n, octal_binary(n));
}
return 0;

or

#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

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

Alogrithm:

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