Program for Octal to Decimal Conversion
Last Updated :
15 Sep, 2023
Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number.
Examples:
Input : 67
Output: 55
Input : 512
Output: 330
Input : 123
Output: 83
The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the octal number, multiply the digit with the proper base (Power of 8) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number.
For Example:
If the octal number is 67.
dec_value = 6*(8^1) + 7*(8^0) = 55
The below diagram explains how to convert an octal number (123) to an equivalent decimal value:

Below is the implementation of the above idea.
C++
// C++ program to convert octal to decimal
#include <iostream>
using namespace std;
// Function to convert octal to decimal
int octalToDecimal(int n)
{
int num = n;
int dec_value = 0;
// Initializing base value to 1, i.e 8^0
int base = 1;
int temp = num;
while (temp) {
// Extracting last digit
int last_digit = temp % 10;
temp = temp / 10;
// Multiplying last digit with appropriate
// base value and adding it to dec_value
dec_value += last_digit * base;
base = base * 8;
}
return dec_value;
}
// Driver program to test above function
int main()
{
int num = 67;
cout << octalToDecimal(num) << endl;
}
Java
// Java program to convert octal to decimal
import java.io.*;
class GFG {
// Function to convert octal to decimal
static int octalToDecimal(int n)
{
int num = n;
int dec_value = 0;
// Initializing base value to 1, i.e 8^0
int base = 1;
int temp = num;
while (temp > 0) {
// Extracting last digit
int last_digit = temp % 10;
temp = temp / 10;
// Multiplying last digit with appropriate
// base value and adding it to dec_value
dec_value += last_digit * base;
base = base * 8;
}
return dec_value;
}
// driver program
public static void main(String[] args)
{
int num = 67;
System.out.println(octalToDecimal(num));
}
}
// This code is contributed
// by Pramod Kumar
Python3
# Python3 program to convert
# octal to decimal
# Function to convert
# octal to decimal
def octalToDecimal(n):
num = n
dec_value = 0
# Initializing base value
# to 1, i.e 8^0
base = 1
temp = num
while (temp):
# Extracting last digit
last_digit = temp % 10
temp = int(temp / 10)
# Multiplying last digit
# with appropriate base
# value and adding it
# to dec_value
dec_value += last_digit * base
base = base * 8
return dec_value
# Driver Code
num = 67
print(octalToDecimal(num))
# This code is contributed by mits
C#
// C# program to convert octal to
// decimal
using System;
class GFG {
// Function to convert octal
// to decimal
static int octalToDecimal(int n)
{
int num = n;
int dec_value = 0;
// Initializing base value
// to 1, i.e 8^0
int b_ase = 1;
int temp = num;
while (temp > 0) {
// Extracting last digit
int last_digit = temp % 10;
temp = temp / 10;
// Multiplying last digit
// with appropriate base
// value and adding it to
// dec_value
dec_value += last_digit * b_ase;
b_ase = b_ase * 8;
}
return dec_value;
}
// driver program
public static void Main()
{
int num = 67;
Console.WriteLine(octalToDecimal(num));
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// JavaScript program to convert octal to decimal
// Function to convert octal to decimal
function octalToDecimal(n)
{
let num = n;
let dec_value = 0;
// Initializing base value to 1, i.e 8^0
let base = 1;
let temp = num;
while (temp) {
// Extracting last digit
let last_digit = temp % 10;
temp = Math.floor(temp / 10);
// Multiplying last digit with appropriate
// base value and adding it to dec_value
dec_value += last_digit * base;
base = base * 8;
}
return dec_value;
}
// Driver program to test above function
let num = 67;
document.write(octalToDecimal(num) + "<br>");
// This code is contributed by Surbhi Tyagi
</script>
PHP
<?php
// PHP program to convert octal to decimal
// Function to convert
// octal to decimal
function octalToDecimal($n)
{
$num = $n;
$dec_value = 0;
// Initializing base value
// to 1, i.e 8^0
$base = 1;
$temp = $num;
while ($temp)
{
// Extracting last digit
$last_digit = $temp % 10;
$temp = $temp / 10;
// Multiplying last digit
// with appropriate base
// value and adding it
// to dec_value
$dec_value += $last_digit * $base;
$base = $base * 8;
}
return $dec_value;
}
// Driver Code
$num = 67;
echo octalToDecimal($num);
// This code is contributed by anuj_67
?>
Time complexity: O(logN) where N is the given number
Auxiliary space: O(1)
Method: Using look up table method
The function octalToDecimal takes an integer n as input, which represents the octal number that needs to be converted to decimal. It initializes an unordered map lookup that maps each octal digit to its decimal equivalent.
It then uses a loop to extract each digit of the octal number from right to left, starting from the least significant digit. For each digit, it multiplies the decimal equivalent of the digit (retrieved from the lookup table) with the appropriate power of 8 (base) and adds it to the decimal variable. The base variable is updated after each iteration by multiplying it with 8. The loop continues until all digits have been processed.
Finally, the decimal variable is returned as the output of the function.
In the main function, an octal number octal_num is initialized and passed as an argument to the octalToDecimal function. The resulting decimal value is printed to the console.
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int octalToDecimal(int n) {
unordered_map<int, int> lookup{
{0, 0}, {1, 1}, {2, 2}, {3, 3},
{4, 4}, {5, 5}, {6, 6}, {7, 7}
};
int decimal = 0;
int base = 1;
while (n > 0) {
int last_digit = n % 10;
decimal += lookup[last_digit] * base;
n /= 10;
base *= 8;
}
return decimal;
}
int main() {
int octal_num = 67;
cout << octalToDecimal(octal_num) << endl;
return 0;
}
Java
import java.util.HashMap;
public class GFG {
public static int octalToDecimal(int n) {
HashMap<Integer, Integer> lookup = new HashMap<>();
lookup.put(0, 0);
lookup.put(1, 1);
lookup.put(2, 2);
lookup.put(3, 3);
lookup.put(4, 4);
lookup.put(5, 5);
lookup.put(6, 6);
lookup.put(7, 7);
int decimal = 0;
int base = 1;
while (n > 0) {
int lastDigit = n % 10;
decimal += lookup.get(lastDigit) * base;
n /= 10;
base *= 8;
}
return decimal;
}
public static void main(String[] args) {
int octalNum = 67;
System.out.println(octalToDecimal(octalNum));
}
}
Python3
def octal_to_decimal(n):
# Define a dictionary to map octal digits to their decimal equivalents
lookup = {
0: 0, 1: 1, 2: 2, 3: 3,
4: 4, 5: 5, 6: 6, 7: 7
}
decimal = 0
base = 1
# Convert octal to decimal
while n > 0:
last_digit = n % 10 # Get the last digit of the octal number
decimal += lookup[last_digit] * base # Add the decimal equivalent to the result
n //= 10 # Remove the last digit from the octal number
base *= 8 # Move to the next octal place value (8^0, 8^1, 8^2, ...)
return decimal
def main():
octal_num = 67
print(octal_to_decimal(octal_num))
if __name__ == "__main__":
main()
C#
using System;
using System.Collections.Generic;
public class GFG
{
// Function to convert octal to decimal
public static int OctalToDecimal(int n)
{
// Lookup table for octal values
Dictionary<int, int> lookup = new Dictionary<int, int>()
{
{0, 0}, {1, 1}, {2, 2}, {3, 3},
{4, 4}, {5, 5}, {6, 6}, {7, 7}
};
int decimalNum = 0;
int baseVal = 1;
// Extracting digits from the octal number and converting to decimal
while (n > 0)
{
int lastDigit = n % 10; // Get the last digit of the octal number
decimalNum += lookup[lastDigit] * baseVal; // Convert the last digit to decimal and add to the result
n /= 10; // Remove the last digit from the octal number
baseVal *= 8; // Move to the next position in the decimal representation (base 8 -> base 10)
}
return decimalNum; // Return the decimal representation of the octal number
}
// Driver code
public static void Main(string[] args)
{
int octalNum = 67;
int decimalValue = OctalToDecimal(octalNum);
Console.WriteLine("Equivalent Decimal Value = " + decimalValue);
}
}
JavaScript
function octalToDecimal(n) {
let lookup = new Map([
[0, 0], [1, 1], [2, 2], [3, 3],
[4, 4], [5, 5], [6, 6], [7, 7]
]);
let decimal = 0;
let base = 1;
while (n > 0) {
let last_digit = n % 10;
decimal += lookup.get(last_digit) * base;
n = Math.floor(n/10);
base *= 8;
}
return decimal;
}
let octal_num = 67;
document.write(octalToDecimal(octal_num));
Time complexity: The time complexity of this algorithm is O(log N), where N is the octal number being converted to decimal. This is because we loop through each digit in the octal number once, and the number of digits in an N-digit octal number is log N.
Auxiliary space: The space complexity of this algorithm is O(1), as we only store a fixed-size lookup table and a few integer variables for the running sum and base value.
Using predefined function
C++
// C++ program to convert octal to decimal
#include <iostream>
using namespace std;
int OctToDec(string n)
{
return stoi(n, 0, 8);
}
int main()
{
string n = "67";
cout << OctToDec(n);
return 0;
}
// This code is contributed by phasing17
Java
// Java program to convert octal to decimal
import java.io.*;
class GFG {
public static int OctToDec(String n)
{
return Integer.parseInt(n, 8);
}
public static void main(String[] args)
{
String n = "67";
System.out.println(OctToDec(n));
}
}
Python3
# Python program to convert octal to decimal
def OctToDec(n):
return int(n, 8);
if __name__ == '__main__':
n = "67";
print(OctToDec(n));
# This code is contributed by 29AjayKumar
C#
using System;
public class GFG{
public static int OctToDec(String n)
{
return Convert.ToInt32(n, 8);
}
static public void Main (){
string n = "67";
Console.WriteLine(OctToDec(n));
}
}
// THIS CODE IS CONTRIBUTED BY RAG2127
JavaScript
<script>
// javascript program to convert octal to decimal
function OctToDec(n)
{
return parseInt(n, 8);
}
var n = "67";
document.write(OctToDec(n));
// This code contributed by Princi Singh
</script>
Method 3: Using recursion
1. The method uses the fact that each digit of an octal number represents a power of 8, starting from the rightmost digit.
2. The method extracts the rightmost digit of the octal number by taking the remainder of the number divided by 10 (i.e., octal % 10) and adds it to the product of the remaining digits and the appropriate power of 8 (i.e., 8 * octal_to_decimal(octal // 10)).
3.This recursive step continues until the entire number has been converted to decimal.
C++
#include <iostream>
using namespace std;
int octal_to_decimal(int octal) {
if (octal == 0) {
return 0;
} else {
return (octal % 10) + 8 * octal_to_decimal(octal / 10);
}
}
int main() {
int octal = 67;
cout << octal_to_decimal(octal) << endl;
return 0;
}
Java
public class OctalToDecimal {
public static int octalToDecimal(int octal) {
if (octal == 0) {
return 0;
} else {
return (octal % 10) + 8 * octalToDecimal(octal / 10);
}
}
public static void main(String[] args) {
int octal = 67;
System.out.println(octalToDecimal(octal));
}
}
Python3
def octal_to_decimal(octal):
if octal == 0:
return 0
else:
return (octal % 10) + 8 * octal_to_decimal(octal // 10)
octal=67
print(octal_to_decimal(octal))
C#
using System;
public class Program
{
public static void Main()
{
int octal = 67;
int decimalNum = OctalToDecimal(octal);
Console.WriteLine(decimalNum);
}
public static int OctalToDecimal(int octal)
{
if (octal == 0)
{
return 0;
}
else
{
return (octal % 10) + 8 * OctalToDecimal(octal / 10);
}
}
}
JavaScript
// Javascript program for the above approach
function octal_to_decimal(octal) {
if (octal == 0) {
return 0;
} else {
return (octal % 10) + 8 * octal_to_decimal(Math.floor(octal / 10));
}
}
let octal = 67;
console.log(octal_to_decimal(octal));
// This code is contributed by rishabmalhdijo
The time complexity of this method is O(log n), where n is the given number
Auxiliary space: O(log n), where n is the given number
C++ Program to Convert Octal Number to Decimal and vice-versa
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