Basic Program to Binary to Octal

#include <stdio.h>
#include <math.h>

int convertBinarytoOctal(long long binaryNumber);
int main()
{
    long long binaryNumber;

    printf("Enter a binary number: ");
    scanf("%lld", &binaryNumber);

    printf("%lld in binary = %d in octal", binaryNumber, convertBinarytoOctal(binaryNumber));

    return 0;
}

int convertBinarytoOctal(long long binaryNumber)
{
    int octalNumber = 0, decimalNumber = 0, i = 0;

    while(binaryNumber != 0)
    {
        decimalNumber += (binaryNumber%10) * pow(2,i);
        ++i;
        binaryNumber/=10;
    }

    i = 1;

    while (decimalNumber != 0)
    {
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }

    return octalNumber;
}

Output

Enter a binary number: 101001
101001 in binary = 51 in octal
import java.util.*;
public class Exercise24 {
public static void main(String[] args) 
    {
        int binnum, binnum1,rem, decnum=0, quot, i=1, j;
        int octnum[] = new int[100];
        Scanner scan = new Scanner(System.in);
		System.out.print("Input a Binary Number : ");
        binnum = scan.nextInt();
        binnum1=binnum;
     
      while(binnum > 0)
        {
            rem = binnum % 10;
            decnum = decnum + rem*i;
            //System.out.println(rem);
            i = i*2;
            binnum = binnum/10;
        }   

		i=1;
        quot = decnum;
		
        while(quot > 0)
        {
            octnum[i++] = quot % 8;
            quot = quot / 8;
        }
		
        System.out.print("Equivalent Octal Value of " +binnum1+ " is :");
        for(j=i-1; j>0; j--)
        {
            System.out.print(octnum[j]);
        }
 System.out.print("\n");
 
    }
}

Sample Output:

Enter Binary Number : 111                                                                                     
Equivalent Octal Value of 111 is :7 

Command Line Program to Convert Binary to Octal

This is a very smart program very short and quick method –

#include
void main(int argc,char *argv[])
{ 
   long int n,r,c,b=1,s=0;
    n=atoi(argv[1]);
    c=n;
    while(c!=0)
    {
    r=c%10;
    s=s+r*b;
    c=c/10;
    b=b*2;
	}
	printf("%lo",s);
	getch();
}