# Write a program for Binary to octal conversion

16 May 2022

Write a program for Binary to octal conversion

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a binary number as the input from the user and give the corresponding octal number as the output.

Input

1000

Output

10

C Program

#include<stdio.h>

#include<math.h>

void BOConvert(long long num)

{

int octal = 0, count = 1, i = 0, pos = 0;

int octalArr[32] = {0};

while(num != 0)

{

int digit = num % 10;

octal += digit * pow(2, i);

i++;

num /= 10;

octalArr[pos] = octal;

if(count % 3 == 0)

{

octal = 0;

i = 0;

pos++;

}

count++;

}

for (int j = pos; j >= 0; j--)

printf("%d",octalArr[j]);

}

int main()

{

long long binary;

printf("Enter binary number: ");

scanf("%lld", &binary);

BOConvert(binary);

return 0;

}

C++ Program

#include <iostream>

#include<math.h>

using namespace std;

int BOConvert(long bin)

{

int oct = 0, dec = 0, i = 0,rem;

while(bin != 0)

{

rem = bin % 10;

int res = rem * pow(2,i);

dec += res;

i++;

bin/=10;

}

i = 1;

while (dec != 0)

{

rem = dec % 8;

oct += rem * i;

dec /= 8;

i *= 10;

}

return oct;

}

int main()

{

long binary;

cout << "Enter a binary number: ";

cin >> binary;

int octal=BOConvert(binary);

cout << octal;

return 0;

}

Java

import java.util.Scanner;

public class Main

{

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

System.out.print("Enter a binary number : ");

int bin = sc.nextInt();

int dec = 0;

int n = 0;

while(bin > 0)

{

int temp = bin%10;

dec += temp*Math.pow(2, n);

bin = bin/10;

n++;

}

int oct[] = new int[20];

int i = 0;

while(dec > 0)

{

int r = dec % 8;

oct[i++] = r;

dec = dec / 8;

}

for(int j = i-1 ; j >= 0 ; j--)

System.out.print(oct[j]);

}

}

Python

bin = int(input("Enter the binary number: "))

octal = 0

octalnum = []

i = 0

mul = 1

c = 1

while bin!=0:

rem = bin % 10

octal = octal + (rem * mul)

if c%3==0:

octalnum.insert(i, octal)

mul = 1

octal = 0

c = 1

i = i+1

else:

mul = mul*2

c = c+1

bin = int(bin / 10)

if c!=1:

octalnum.insert(i, octal)

#print("\nEquivalent Octal Value = ", end="")

while i>=0:

print(str(octalnum[i]), end="")

i = i-1

print()

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023