Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
C++ Program For Decimal To Octal Conversion
Next article icon

C++ Program For Binary To Octal Conversion

Last Updated : 23 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples:  

Input: 110001110
Output: 616

Input: 1111001010010100001.010110110011011
Output: 1712241.26633 

Simple Approach

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

  1. Get the length of the 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 a min number of 0’s in the beginning to make the length of the left substring a multiple of 3.
  3. If right_len is not a multiple of 3 add a min number of 0’s in the end to make the length of the 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.

Below is the C++ program to implement the above approach:

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 code int main() {     string bin = "1111001010010100001.010110110011011";     cout << "Octal number = " << convertBinToOct(bin);     return 0; } 

Output
Octal number = 1712241.26633

The complexity of the above method

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

Auxiliary space: O(1).

Optimized Approach

The steps for this approach are as follows:

  1. Convert the given binary number into groups of three digits starting from the rightmost side.
  2. Convert each group of three digits to its corresponding octal digit.
  3. Concatenate the octal digits obtained in step 2 to get the octal equivalent of the given binary number.

Below is the C++ program to implement the above approach:

C++
// C++ program to convert binary // to octal #include <cmath> #include <iostream> #include <string> using namespace std;  // Function to convert binary to // octal string binaryToOctal(string binary) {     // Check if the binary number is valid     if (binary.find_first_not_of("01.") != string::npos) {         return "Invalid binary number";     }      // Convert the integer part of the binary number     // to octal     int decimal = stoi(binary.substr(0, binary.find('.')),                        nullptr, 2);     string octal = "";     while (decimal > 0) {         octal = to_string(decimal % 8) + octal;         decimal /= 8;     }      // Convert the fractional part of the binary number     // to octal     if (binary.find('.') != string::npos) {         double fractional = stod(             "0." + binary.substr(binary.find('.') + 1));         octal += ".";         for (int i = 0; i < 5; i++) {             fractional *= 8;             octal += to_string((int)floor(fractional));             fractional -= floor(fractional);         }     }      return octal; }  // Dtriver code int main() {     string binary1 = "110001110";     string octal1 = binaryToOctal(binary1);     cout << "Octal equivalent of " << binary1 << " is "          << octal1 << endl;      string binary2 = "1111001010010100001";     string octal2 = binaryToOctal(binary2);     cout << "Octal equivalent of " << binary2 << " is "          << octal2 << endl;      string binary3 = "11011.10";     string octal3 = binaryToOctal(binary3);     cout << "Octal equivalent of " << binary3 << " is "          << octal3 << endl;      string binary4 = "1002";     string octal4 = binaryToOctal(binary4);     cout << "Octal equivalent of " << binary4 << " is "          << octal4 << endl;      return 0; } 

Output
Octal equivalent of 110001110 is 616 Octal equivalent of 1111001010010100001 is 1712241 Octal equivalent of 11011.10 is 33.06314 Octal equivalent of 1002 is Invalid binary number

Complexity of the above method

Time Complexity: O(n), where n is the number of digits in the given binary number. 
Auxiliary Space: O(n/3), since we need to store the octal digits obtained for each group of three binary digits.


Next Article
C++ Program For Decimal To Octal Conversion
author
kartik
Improve
Article Tags :
  • C++ Programs
  • C++
  • C Conversion Programs
Practice Tags :
  • CPP

Similar Reads

  • C++ Program For Binary To Decimal Conversion
    The binary number system uses only two digits 0 and 1 to represent an integer and the Decimal number system uses ten digits 0 to 9 to represent a number. In this article, we will discuss the program for Binary to Decimal conversion in C++. Algorithm to Convert Binary Numbers to DecimalInitialize a v
    4 min read
  • C++ Program For Decimal To Binary Conversion
    Binary Numbers uses only 0 and 1 (base-2), while Decimal Number uses 0 to 9 (base-10). In this article, we will learn to implement a C++ program to convert Decimal numbers to Binary Numbers. The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. Recomm
    3 min read
  • C++ Program For Decimal To Octal Conversion
    The octal numbers are a base 8 number system that uses digits from 0-7 and the decimal numbers are a base 10 numbers system that uses 10 digits from 0-9 to represent any numeric value. In this article, we will learn how to write a C++ program to convert a given decimal number into an equivalent octa
    2 min read
  • C++ 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 an equivalent decimal number. Examples: Input : 67Output: 55 Input : 512Output: 330 Input : 123Output: 83 1. Simple ApproachThe idea is to extract the digits of a given octal number starting from the ri
    2 min read
  • C++ Program For char to int Conversion
    In C++, we cannot directly perform numeric operations on characters that represent numeric values. If we attempt to do so, the program will interpret the character's ASCII value instead of the numeric value it represents. In this article, we will learn how to convert char to int in C++. Example: Inp
    2 min read
  • C++ Program For Boolean to String Conversion
    In this article, we will see how to convert a boolean to a string using a C++ program. In boolean algebra, there are only two values 0 and 1 which represent False and True. Thus, boolean to string conversion can be stated as: Boolean -> String 1 -> True0 -> False Example: Input: 1 Output: T
    2 min read
  • C++ Program For Hexadecimal To Decimal Conversion
    The hexadecimal numbers are base 16 numbers that use 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all digits. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). Decimal numbers are base 10 numbers with 10 symbols to represent all digits. In this article, we will l
    3 min read
  • C++ Program For Decimal To Hexadecimal Conversion
    In this article, we will learn to write a C++ program to convert a decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. In the decimal system, we use ten digits (0 to 9) to represent a number, while in the hexadecimal system, we use sixte
    3 min read
  • C++ Program For Double to String Conversion
    Here, we will build a C++ program for double to string conversion using various methods i.e. Using to_stringUsing stringstreamUsing sprintfUsing lexical_cast We will keep the same input in all the mentioned approaches and get an output accordingly. Input: n = 456321.7651234 Output: string: 456321.76
    2 min read
  • C++ Program For Binary Search
    Binary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the pro
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences