The Wayback Machine - https://web.archive.org/web/20240816190926/https://www.geeksforgeeks.org/convert-binary-number-octal/
Open In App

Program to convert a binary number to octal

Last Updated : 05 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The problem is to convert the given binary number (represented as string) to its equivalent octal number. The input could be very large and may not fit even into unsigned long long int.

Examples:  

Input : 110001110
Output : 616

Input  : 1111001010010100001.010110110011011
Output : 1712241.26633 

The idea is to consider the binary input as a string of characters and then follow the steps: 

  1. Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.
  2. If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3.
  3. If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3.
  4. Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result.
  5. If in between a decimal(‘.’) is encountered then add it to the result.

C++




// C++ implementation to convert a binary number
// to octal number
#include <bits/stdc++.h>
using namespace std;
   
// function to create map between binary
// number and its equivalent octal
void createMap(unordered_map<string, char> *um)
{
    (*um)["000"] = '0';
    (*um)["001"] = '1';
    (*um)["010"] = '2';
    (*um)["011"] = '3';
    (*um)["100"] = '4';
    (*um)["101"] = '5';
    (*um)["110"] = '6';
    (*um)["111"] = '7';    
}
   
// Function to find octal equivalent of binary
string convertBinToOct(string bin)
{
    int l = bin.size();
    int t = bin.find_first_of('.');
       
    // length of string before '.'
    int len_left = t != -1 ? t : l;
       
    // add min 0's in the beginning to make
    // left substring length divisible by 3 
    for (int i = 1; i <= (3 - len_left % 3) % 3; i++)
        bin = '0' + bin;
       
    // if decimal point exists    
    if (t != -1)    
    {
        // length of string after '.'
        int len_right = l - len_left - 1;
           
        // add min 0's in the end to make right
        // substring length divisible by 3 
        for (int i = 1; i <= (3 - len_right % 3) % 3; i++)
            bin = bin + '0';
    }
       
    // create map between binary and its
    // equivalent octal code
    unordered_map<string, char> bin_oct_map;
    createMap(&bin;_oct_map);
       
    int i = 0;
    string octal = "";
       
    while (1)
    {
        // one by one extract from left, substring
        // of size 3 and add its octal code
        octal += bin_oct_map[bin.substr(i, 3)];
        i += 3;
        if (i == bin.size())
            break;
               
        // if '.' is encountered add it to result
        if (bin.at(i) == '.')    
        {
            octal += '.';
            i++;
        }
    }
       
    // required octal number
    return octal;    
}
   
// Driver program to test above
int main()
{
    string bin = "1111001010010100001.010110110011011";
    cout << "Octal number = "
         << convertBinToOct(bin);
    return 0;     
}  


Java




// Java implementation to convert a 
// binary number to octal number 
import java.io.*;
import java.util.*;
  
class GFG{
  
// Function to create map between binary
// number and its equivalent hexadecimal
static void createMap(Map<String, Character> um)
{
    um.put("000", '0');
    um.put("001", '1');
    um.put("010", '2');
    um.put("011", '3');
    um.put("100", '4');
    um.put("101", '5');
    um.put("110", '6');
    um.put("111", '7');
}
  
// Function to find octal equivalent of binary
static String convertBinToOct(String bin)
{
    int l = bin.length();
    int t = bin.indexOf('.');
  
    // Length of string before '.'
    int len_left = t != -1 ? t : l;
  
    // Add min 0's in the beginning to make
    // left substring length divisible by 3
    for(int i = 1; 
            i <= (3 - len_left % 3) % 3; 
            i++)
        bin = '0' + bin;
  
    // If decimal point exists
    if (t != -1)
    {
          
        // Length of string after '.'
        int len_right = l - len_left - 1;
  
        // add min 0's in the end to make right
        // substring length divisible by 3
        for(int i = 1;
                i <= (3 - len_right % 3) % 3;
                i++)
            bin = bin + '0';
    }
  
    // Create map between binary and its
    // equivalent octal code
    Map<String, 
        Character> bin_oct_map = new HashMap<String, 
                                             Character>();
    createMap(bin_oct_map);
  
    int i = 0;
    String octal = "";
  
    while (true)
    {
          
        // One by one extract from left, substring
        // of size 3 and add its octal code
        octal += bin_oct_map.get(
            bin.substring(i, i + 3));
        i += 3;
          
        if (i == bin.length())
            break;
  
        // If '.' is encountered add it to result
        if (bin.charAt(i) == '.')
        {
            octal += '.';
            i++;
        }
    }
  
    // Required octal number
    return octal;
}
  
// Driver code
public static void main(String[] args)
{
    String bin = "1111001010010100001.010110110011011";
    System.out.println("Octal number = " +
                        convertBinToOct(bin));
}
}
  
// This code is contributed by jithin


Python3




# Python3 implementation to convert a binary number 
# to octal number 
  
# function to create map between binary 
# number and its equivalent octal 
def createMap(bin_oct_map):
    bin_oct_map["000"] = '0'
    bin_oct_map["001"] = '1'
    bin_oct_map["010"] = '2'
    bin_oct_map["011"] = '3'
    bin_oct_map["100"] = '4'
    bin_oct_map["101"] = '5'
    bin_oct_map["110"] = '6'
    bin_oct_map["111"] = '7'
  
# Function to find octal equivalent of binary 
def convertBinToOct(bin): 
    l = len(bin)
      
    # length of string before '.' 
    t = -1
    if '.' in bin:
        t = bin.index('.') 
        len_left = t
    else:
        len_left = l 
      
    # add min 0's in the beginning to make 
    # left substring length divisible by 3 
    for i in range(1, (3 - len_left % 3) % 3 + 1):
        bin = '0' + bin
      
    # if decimal point exists 
    if (t != -1): 
          
        # length of string after '.' 
        len_right = l - len_left - 1
          
        # add min 0's in the end to make right 
        # substring length divisible by 3 
        for i in range(1, (3 - len_right % 3) % 3 + 1):
            bin = bin + '0'
      
    # create dictionary between binary and its 
    # equivalent octal code 
    bin_oct_map = {}
    createMap(bin_oct_map)
    i = 0
    octal = ""
      
    while (True) :
          
        # one by one extract from left, substring 
        # of size 3 and add its octal code 
        octal += bin_oct_map[bin[i:i + 3]] 
        i += 3
        if (i == len(bin)): 
            break
              
        # if '.' is encountered add it to result 
        if (bin[i] == '.'):
            octal += '.'
            i += 1
              
    # required octal number 
    return octal
  
# Driver Code
bin = "1111001010010100001.010110110011011"
print("Octal number = ", 
       convertBinToOct(bin))
  
# This code is contributed 
# by Atul_kumar_Shrivastava


C#




// C# implementation to convert a 
// binary number to octal number 
  
using System;
using System.Collections.Generic;
  
public class GFG{
  
// Function to create map between binary
// number and its equivalent hexadecimal
static void createMap(Dictionary<String, char> um)
{
    um.Add("000", '0');
    um.Add("001", '1');
    um.Add("010", '2');
    um.Add("011", '3');
    um.Add("100", '4');
    um.Add("101", '5');
    um.Add("110", '6');
    um.Add("111", '7');
}
  
// Function to find octal equivalent of binary
static String convertBinToOct(String bin)
{
    int l = bin.Length;
    int t = bin.IndexOf('.');
    int i = 0;
    // Length of string before '.'
    int len_left = t != -1 ? t : l;
  
    // Add min 0's in the beginning to make
    // left substring length divisible by 3
    for(i = 1; 
            i <= (3 - len_left % 3) % 3; 
            i++)
        bin = '0' + bin;
  
    // If decimal point exists
    if (t != -1)
    {
          
        // Length of string after '.'
        int len_right = l - len_left - 1;
  
        // add min 0's in the end to make right
        // substring length divisible by 3
        for(i = 1;
                i <= (3 - len_right % 3) % 3;
                i++)
            bin = bin + '0';
    }
  
    // Create map between binary and its
    // equivalent octal code
    Dictionary<String, 
        char> bin_oct_map = new Dictionary<String, 
                                             char>();
    createMap(bin_oct_map);
  
    i = 0;
    String octal = "";
  
    while (true)
    {
          
        // One by one extract from left, substring
        // of size 3 and add its octal code
        octal += bin_oct_map[
            bin.Substring(i,  3)];
        i += 3;
          
        if (i == bin.Length)
            break;
  
        // If '.' is encountered add it to result
        if (bin[i] == '.')
        {
            octal += '.';
            i++;
        }
    }
  
    // Required octal number
    return octal;
}
  
// Driver code
public static void Main(String[] args)
{
    String bin = "1111001010010100001.010110110011011";
    Console.WriteLine("Octal number = " +
                        convertBinToOct(bin));
}
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
  
// Javascript implementation to convert a
// binary number to octal number
  
// Function to create map between binary
// number and its equivalent hexadecimal
function createMap(um) 
{
    um.set("000", '0');
    um.set("001", '1');
    um.set("010", '2');
    um.set("011", '3');
    um.set("100", '4');
    um.set("101", '5');
    um.set("110", '6');
    um.set("111", '7');
}
  
// Function to find octal equivalent of binary
function convertBinToOct(bin)
{
      
    let l = bin.length;
    let t = bin.indexOf('.');
  
    // Length of string before '.'
    let len_left = t != -1 ? t : l;
  
    // Add min 0's in the beginning to make
    // left substring length divisible by 3
    for(let i = 1; 
            i <= (3 - len_left % 3) % 3; 
            i++)
        bin = '0' + bin;
  
    // If decimal point exists
    if (t != -1)
    {
          
        // Length of string after '.'
        let len_right = l - len_left - 1;
  
        // add min 0's in the end to make right
        // substring length divisible by 3
        for(let i = 1; 
                i <= (3 - len_right % 3) % 3;
                i++)
            bin = bin + '0';
    }
  
    // Create map between binary and its
    // equivalent octal code
    let bin_oct_map = new Map();
  
    createMap(bin_oct_map);
  
    let i = 0;
    let octal = "";
  
    while (true) 
    {
          
        // One by one extract from left, substring
        // of size 3 and add its octal code
        octal += bin_oct_map.get(bin.substr(i, 3));
        i += 3;
  
        if (i == bin.length)
            break;
  
        // If '.' is encountered add it to result
        if (bin.charAt(i) == '.')
        {
            octal += '.';
            i++;
        }
    }
  
    // Required octal number
    return octal;
}
  
// Driver code
let bin = "1111001010010100001.010110110011011";
document.write("Octal number = " + 
               convertBinToOct(bin));
  
// This code is contributed by gfgking
  
</script>


Output

Octal number = 1712241.26633

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)

 



Similar Reads

Program to Convert Octal Number to Binary Number
Given an Octal number as input, the task is to convert that number to Binary number. Examples: Input : Octal = 345Output : Binary = 11100101Explanation : Equivalent binary value of 3: 011Equivalent binary value of 4: 100Equivalent binary value of 5: 101 Input : Octal = 120Output : Binary = 1010000 Octal Number: An Octal number is a positional numer
9 min read
Program to convert float decimal to Octal number
Write a program that converts a floating-point decimal number into its octal format. The program should take a number and the precision for the octal fractional part as inputs from the user. It should calculate and provide its correct octal representation as output. Examples: Input: Number = 123.45, No. of decimal places (Precision): 5Output: 173.3
8 min read
Program to Convert Hexadecimal to Octal
Given a Hexadecimal number, the task is to convert it into an Octal number.Examples: Input: Hexadecimal = 1AC Output: Binary = 0654 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Grouping in terms of 3: 000 110 101 100 Equivalent octal value of 000: 0 Equivalent octal value of 1
15 min read
Octal equivalents of connected components in Binary valued graph
Given a binary valued undirected graph with V vertices and E edges, the task is to find the octal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: Chain = 0 1 Octal equivalent = 1 Chain = 0 0 0 Octal eq
15+ min read
Program for Octal to Decimal Conversion
Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number. Examples: Input : 67Output: 55Input : 512Output: 330Input : 123Output: 83The 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 dig
11 min read
Program for Decimal to Octal Conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent octal number. i.e convert the number with base value 10 to base value 8. The base value of a number system determines the number of digits used to represent a numeric value. For example, the binary number system uses two digits 0 and 1
10 min read
Check if Decimal representation of an Octal number is divisible by 7
Given an Octal number N. The task is to write a program to check if the Decimal representation of the given octal number N is divisible by 7 or not. Examples: Input: N = 112 Output: NO Equivalent Decimal = 74 7410 = 7 * 10 1 + 4 * 100 1128 = 1 * 82 + 1 * 81 + 2 * 80 Input: N = 25 Output: YES Decimal Equivalent = 21 The idea is to note that, 8 % 7 w
4 min read
Largest Even and Odd N-digit numbers in Octal Number System
Given an integer N, the task is to find the largest even and odd N-digit numbers in Octal Number System.Examples: Input: N = 4 Output: Even : 7776 Odd : 7777Input: N = 2 Output: Even : 76 Odd : 77 Approach: To get the largest number, the digits of the number have to be maximum possible. Since in the octal number system, the maximum digit is '7'. So
4 min read
Check if an Octal number is Even or Odd
Given an Octal number N, check whether it is even or odd.Examples: Input: N = 7234 Output: Even Input: N = 333333333 Output: Odd Naive Approach: Convert the number from Octal base to Decimal base.Then check if the number is even or odd, which can be easily checked by dividing by 2. Time Complexity: O(N)Efficient approach: Since Octal numbers contai
4 min read
Largest N digit Octal number which is a Perfect square
Given a natural number N, the task is to find the largest N digit Octal number which is a perfect square.Examples: Input: N = 1 Output: 4 Explanation: 4 is the largest 1 digit Octal number which is also perfect squareInput: N = 2 Output: 61 Explanation: 49 is the largest number which is a 2-Digit Octal Number and also a perfect square. Therefore 49
10 min read
Check if number is palindrome or not in Octal
Given a number which may be in octal or in decimal. If the number is not octal then convert it into octal then check if it is palindrome or not. If it is palindrome then print 1 otherwise print 0. If the number is already in octal then check if the number is palindrome or not.Examples : Input :n = 111 Output : Yes Explanation: all digits of 111 are
7 min read
Program to convert a Binary Number to Hexa-Decimal Number
Given a Binary Number, the task is to convert this Binary number to its equivalent Hexa-Decimal Number.Examples: Input: 100000101111 Output: 82F Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1111. Here, 1000 is equivalent to 8, 0010 is equivalent to 2 and 1111 is equivalent to F Therefore, the number becomes 82FInput:10101
10 min read
Program to convert a binary number to hexadecimal number
Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int. Examples:  Input: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B Approach 1: Binary Number: A binary number is a num
13 min read
Decimal to octal conversion with minimum use of arithmetic operators
Given a decimal number n without floating-point. The problem is to convert the decimal number to octal number with minimum use of arithmetic operators. Examples: Input : n = 10 Output : 12 12 is octal equivalent of decimal 10. Input : n = 151 Output : 227 Approach: Following are the steps: Perform decimal to binary conversion without using arithmet
8 min read
Count of Octal numbers upto N digits
Given an integer N, the task is to find the count of natural octal numbers up to N digits. Examples: Input: N = 1 Output: 7 Explanation: 1, 2, 3, 4, 5, 6, 7 are 1 digit Natural Octal numbers.Input: N = 2 Output: 63 Explanation: There are a total of 56 two digit octal numbers and 7 one digit octal numbers. Therefore, 56 + 7 = 63. Approach: On observ
4 min read
Largest and Smallest N-digit Octal Numbers
Given an integer N, the task is to find the smallest and largest N-digit numbers in Octal Number System. Examples: Input: N = 4 Output: Largest: 7777 Smallest: 1000 Input: N = 2 Output: Largest: 77 Smallest: 10 Approach: The following steps can be followed to compute the required answer: Largest Number: To get the largest number, every digit of the
5 min read
Count numbers up to N having digit D in its octal representation
Given a positive integer N and an integer D representing a digit, the task is to count the numbers in the range[1, N] such that at least one digit in octal representation of the number is d. Examples: Input: N = 20, D = 7Output: 2Explanation: The numbers in the range [1, 20] having digit 7 in their octal representation are 7 and 15. Therefore, the
6 min read
Queries to count numbers from a range which does not contain digit K in their decimal or octal representation
Given an integer K and an array Q[][] consisting of N queries of type {L, R}, the task for each query is to print the count of numbers from the range [L, R] that doesn't contain the digit K in their decimal representation or octal representation. Examples: Input: K = 7, Q[][] = {{1, 15}}Output: 13Explanation:Only number 7 and 15 contains digit K in
9 min read
Program to Convert Hexadecimal Number to Binary
Given a Hexadecimal number as an input, the task is to convert that number to a Binary number.Examples: Input: Hexadecimal = 1AC5 Output: Binary = 0001101011000101 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Equivalent binary value of 5: 0101 Input: Hexadecimal = 5D1F Output:
14 min read
Number of steps required to convert a binary number to one
Given a binary string str, the task is to print the numbers of steps required to convert it to one by the following operations: If 'S' is having odd value, add 1 to it.If 'S' is having even value, divide it by 2.Examples: Input: str = "1001001" Output: 12 Input: str = "101110" Output: 8Number '101110' is even, after dividing it by 2 we get an odd n
7 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1". Examples : Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}Output: 3Explanation: One p
8 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Program to Convert BCD number into Decimal number
Given a BCD (Binary Coded Decimal) number, the task is to convert the BCD number into its equivalent Decimal number. Examples: Input: BCD = 100000101000 Output: 828 Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1000. Here, 1000 is equivalent to 8 and 0010 is equivalent to 2. So, the number becomes 828. Input: BCD = 1001000
10 min read
Program to convert given Binary to its equivalent ASCII character string
Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Examples: Input: str = "0110000101100010"Output: abExplanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'.01100010 = 98, ASCII value of 98 is 'b'.Therefore, the required
9 min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two parameters root1 and root2.Here, root1 and root2, a
8 min read
Convert all numbers in range [L, R] to binary number
Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. Examples: Input: L = 1, R = 4Output: 11011100Explanation: The binary representation of the numbers 1, 2, 3 and 4 are: 1 = (1)22 = (10)23 = (11)24 = (100)2 Input: L = 2, R = 8Output:10111001011101111000 Approach: The problem can be solved
5 min read
Convert decimal fraction to binary number
Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. Examples: Input: n = 2.47, k = 5 Output: 10.01111 Input: n = 6.986 k = 8 Output: 110.11111100We strongly recommend that you click here and practice it, before moving on to the solution. A) Convert the integr
9 min read
three90RightbarBannerImg