Program to Convert Octal Number to Binary Number
Last Updated :
10 Apr, 2023
Given an Octal number as input, the task is to convert that number to Binary number.
Examples:
Input : Octal = 345
Output : Binary = 11100101
Explanation :
Equivalent binary value of 3: 011
Equivalent binary value of 4: 100
Equivalent binary value of 5: 101
Input : Octal = 120
Output : Binary = 1010000
Octal Number: An Octal number is a positional numeral system with a radix, or base, of 8 and uses eight distinct symbols.
Binary Number: A Binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 (zero) and 1 (one).
To convert an Octal number to Binary, the binary equivalent of each digit of the octal number is evaluated and combined at the end to get the equivalent binary number.

Below is the implementation of the above approach:
C++
// C++ program to convert
// Octal number to Binary
#include <iostream>
using namespace std;
// Function to convert an
// Octal to Binary Number
string OctToBin(string octnum)
{
long int i = 0;
string binary = "";
while (octnum[i]) {
switch (octnum[i]) {
case '0':
binary += "000";
break;
case '1':
binary += "001";
break;
case '2':
binary += "010";
break;
case '3':
binary += "011";
break;
case '4':
binary += "100";
break;
case '5':
binary += "101";
break;
case '6':
binary += "110";
break;
case '7':
binary += "111";
break;
default:
cout << "\nInvalid Octal Digit "
<< octnum[i];
break;
}
i++;
}
return binary;
}
// Driver code
int main()
{
// Get the Hexadecimal number
string octnum = "345";
// Convert Octal to Binary
cout << "Equivalent Binary Value = "
<< OctToBin(octnum);
return 0;
}
Java
// Java program to convert
// Octal number to Binary
import java.util.*;
class Solution
{
// Function to convert an
// Octal to Binary Number
static String OctToBin(String octnum)
{
long i = 0;
String binary = "";
while (i<octnum.length()) {
char c=octnum.charAt((int)i);
switch (c) {
case '0':
binary += "000";
break;
case '1':
binary += "001";
break;
case '2':
binary += "010";
break;
case '3':
binary += "011";
break;
case '4':
binary += "100";
break;
case '5':
binary += "101";
break;
case '6':
binary += "110";
break;
case '7':
binary += "111";
break;
default:
System.out.println( "\nInvalid Octal Digit "+ octnum.charAt((int)i));
break;
}
i++;
}
return binary;
}
// Driver code
public static void main(String args[])
{
// Get the Hexadecimal number
String octnum = "345";
// Convert Octal to Binary
System.out.println( "Equivalent Binary Value = "+ OctToBin(octnum));
}
}
//contributed by Arnab Kundu
Python3
# Python3 program to convert
# Octal number to Binary
# defining a function that returns
# binary equivalent of the number
def OctToBin(octnum):
binary = "" # initialising bin as String
# While loop to extract each digit
while octnum != 0:
# extracting each digit
d = int(octnum % 10)
if d == 0:
# concatenation of string using join function
binary = "".join(["000", binary])
elif d == 1:
# concatenation of string using join function
binary = "".join(["001", binary])
elif d == 2:
# concatenation of string using join function
binary = "".join(["010", binary])
elif d == 3:
# concatenation of string using join function
binary = "".join(["011", binary])
elif d == 4:
# concatenation of string using join function
binary = "".join(["100", binary])
elif d == 5:
# concatenation of string using join function
binary = "".join(["101", binary])
elif d == 6:
# concatenation of string using join function
binary = "".join(["110",binary])
elif d == 7:
# concatenation of string using join function
binary = "".join(["111", binary])
else:
# an option for invalid input
binary = "Invalid Octal Digit"
break
# updating the oct for while loop
octnum = int(octnum / 10)
# returning the string binary that stores
# binary equivalent of the number
return binary
# Driver Code
octnum = 345
# value of function stored final_bin
final_bin = "" + OctToBin(octnum)
# result is printed
print("Equivalent Binary Value =", final_bin)
# This code is contributed by Animesh_Gupta
C#
// C# program to convert Octal number to Binary
class GFG
{
// Function to convert an
// Octal to Binary Number
static string OctToBin(string octnum)
{
int i = 0;
string binary = "";
while (i < octnum.Length)
{
char c = octnum[i];
switch (c)
{
case '0':
binary += "000";
break;
case '1':
binary += "001";
break;
case '2':
binary += "010";
break;
case '3':
binary += "011";
break;
case '4':
binary += "100";
break;
case '5':
binary += "101";
break;
case '6':
binary += "110";
break;
case '7':
binary += "111";
break;
default:
System.Console.WriteLine( "\nInvalid Octal Digit "+
octnum[i]);
break;
}
i++;
}
return binary;
}
// Driver code
static void Main()
{
// Get the Hexadecimal number
string octnum = "345";
// Convert Octal to Binary
System.Console.WriteLine("Equivalent Binary Value = " +
OctToBin(octnum));
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to convert
// Octal number to Binary
// Function to convert an
// Octal to Binary Number
function OctToBin($octnum)
{
$i = 0;
$binary = (string)"";
while ($i != strlen($octnum))
{
switch ($octnum[$i])
{
case '0':
$binary.= "000";
break;
case '1':
$binary .= "001";
break;
case '2':
$binary .= "010";
break;
case '3':
$binary .= "011";
break;
case '4':
$binary .= "100";
break;
case '5':
$binary .= "101";
break;
case '6':
$binary .= "110";
break;
case '7':
$binary .= "111";
break;
default:
echo("\nInvalid Octal Digit ".
$octnum[$i]);
break;
}
$i++;
}
return $binary;
}
// Driver code
// Get the Hexadecimal number
$octnum = "345";
/// Convert Octal to Binary
echo("Equivalent Binary Value = " .
OctToBin($octnum));
// This code is contributed
// by PrinciRaj1992
JavaScript
<script>
// JavaScript program to convert
// Octal number to Binary
// Function to convert an
// Octal to Binary Number
function OctToBin(octnum)
{
let i = 0;
let binary = "";
while (i<octnum.length) {
let c=octnum[i];
switch (c) {
case '0':
binary += "000";
break;
case '1':
binary += "001";
break;
case '2':
binary += "010";
break;
case '3':
binary += "011";
break;
case '4':
binary += "100";
break;
case '5':
binary += "101";
break;
case '6':
binary += "110";
break;
case '7':
binary += "111";
break;
default:
document.write( "<br>Invalid Octal Digit "+ octnum[i]);
break;
}
i++;
}
return binary;
}
// Driver code
// Get the Hexadecimal number
let octnum = "345";
// Convert Octal to Binary
document.write( "Equivalent Binary Value = "+ OctToBin(octnum));
// This code is contributed by avanitrachhadiya2155
</script>
Output: Equivalent Binary Value = 011100101
Time complexity: O(n) where n is no of digits in a given number.
Auxiliary space: O(n) it is using extra space for binary string.
define function to convert octal to binary in python:
Approach:
n this program, we define a function called octal_to_binary that takes an octal number as input and returns its binary equivalent.
The function works by first converting the octal number to decimal using the repeated division by 8 technique. Once we have the decimal equivalent, we can convert it to binary using the repeated division by 2 technique.
Finally, we call the octal_to_binary function with a sample octal number of 777, and then print the binary equivalent using an f-string.
C++
#include <iostream>
#include <cmath>
using namespace std;
int octal_to_binary(int octal) {
// Converting Octal to Decimal
int decimal = 0;
int power = 0;
while (octal != 0) {
decimal += (octal % 10) * pow(8, power);
octal /= 10;
power++;
}
// Converting Decimal to Binary
int binary = 0;
int digit_place = 1;
while (decimal != 0) {
binary += (decimal % 2) * digit_place;
decimal /= 2;
digit_place *= 10;
}
return binary;
}
int main() {
// Sample Input
int octal_number = 777;
// Octal to Binary Conversion
int binary_number = octal_to_binary(octal_number);
// Output
cout << binary_number << endl;
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static int octal_to_binary(int octal)
{
// Converting Octal to Decimal
int decimal = 0;
int power = 0;
while (octal != 0) {
decimal += (octal % 10) * Math.pow(8, power);
octal /= 10;
power++;
}
// Converting Decimal to Binary
int binary = 0;
int digit_place = 1;
while (decimal != 0) {
binary += (decimal % 2) * digit_place;
decimal /= 2;
digit_place *= 10;
}
return binary;
}
public static void main(String[] args)
{
// Sample Input
int octal_number = 777;
// Octal to Binary Conversion
int binary_number = octal_to_binary(octal_number);
// Output
System.out.println(binary_number);
}
}
Python3
# Octal to Binary Conversion Function
def octal_to_binary(octal):
# Converting Octal to Decimal
decimal = 0
power = 0
while octal != 0:
decimal += (octal % 10) * pow(8, power)
octal //= 10
power += 1
# Converting Decimal to Binary
binary = 0
digit_place = 1
while decimal != 0:
binary += (decimal % 2) * digit_place
decimal //= 2
digit_place *= 10
return binary
# Sample Input
octal_number = 777
# Octal to Binary Conversion
binary_number = octal_to_binary(octal_number)
# Output
print(f"The binary equivalent of {octal_number} is {binary_number}")
C#
using System;
class Program {
static int octal_to_binary(int octal) {
// Converting Octal to Decimal
int decimalNumber = 0;
int power = 0;
while (octal != 0) {
decimalNumber += (octal % 10) * (int)Math.Pow(8, power);
octal /= 10;
power++;
}
// Converting Decimal to Binary
int binaryNumber = 0;
int digit_place = 1;
while (decimalNumber != 0) {
binaryNumber += (decimalNumber % 2) * digit_place;
decimalNumber /= 2;
digit_place *= 10;
}
return binaryNumber;
}
static void Main() {
// Sample Input
int octalNumber = 777;
// Octal to Binary Conversion
int binaryNumber = octal_to_binary(octalNumber);
// Output
Console.WriteLine(binaryNumber);
}
}
JavaScript
function octal_to_binary(octal)
{
// Converting Octal to Decimal
let decimal = 0;
let power = 0;
while (octal != 0) {
decimal += (octal % 10) * Math.pow(8, power);
octal = Math.floor(octal / 10);
power++;
}
// Converting Decimal to Binary
let binary = 0;
let digit_place = 1;
while (decimal != 0) {
binary += (decimal % 2) * digit_place;
decimal = Math.floor(decimal / 2);
digit_place *= 10;
}
return binary;
}
// Sample Input
const octal_number = 777;
// Octal to Binary Conversion
const binary_number = octal_to_binary(octal_number);
// Output
console.log(`The binary equivalent of ${octal_number} is ${binary_number}`);
OutputThe binary equivalent of 777 is 111111111
The time complexity: O(log n). Where n is the input octal number
The auxiliary space : O(1) .
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem