Binary is a base-2 numeral system used in computing that represents numbers using only two digits, 0 and 1. C++ provides built-in functions and methods to perform this conversion. Among these numerical systems, the binary numeral system stands out as a fundamental building block, and is widely used in the realm of computing. In this blog, we will explore the most straightforward and simplistic approach to convert binary to number in C++, an essential skill for novice programmers and those seeking a quick and easy guide. So, let’s start the journey of binary to number conversion in C++.
Why is Converting Binary To Number In C++ is needed?
.There are the some reasons why converting binary to number in C++ is needed:
- Input Processing: Binary data is often received or stored in the form of strings or arrays of 0s and 1s. Converting binary to number in C++ allows programmers to process this input data and perform operations such as arithmetic calculations, comparisons, and data manipulation.
- Output Display: Binary data may need to be converted to a human-readable format for display or printing.
- Data Representation: Binary data is used in various data structures and algorithms, such as bit manipulation, bitwise operations, and binary file handling.
How To Convert Binary To Number In C++
Here are six different approaches to how to convert binary to number in C++ with detailed solution steps, code, and output for each approach:
- Using Standard Library Functions
- Using Bitwise Operators
- Using Standard Library Functions for String Manipulation
- Using Algorithm Library
- Using Custom Logic
- Using Bit Manipulation
Let’s dive in more with examples to each approach.
Approach 1:Using Standard Library Functions
This approach uses the standard library function stoi() to convert a binary string to a number.
Pros:
- Simple and easy to understand.
- Relies on standard library functions, so it is likely to be optimized and efficient.
- Handles input validation for invalid binary strings.
Cons:
- Requires C++11 or later.
- Does not support leading zeros in binary strings.
- Relies on exceptions for error handling, which may impact performance in certain scenarios.
Code:
#include <iostream>
#include <string>
int main() {
std::string binaryString = "101010"; // Binary string to be converted
int number = std::stoi(binaryString, nullptr, 2); // Convert binary string to integer using stoi() with base 2
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 42
Code Explanation
- The stoi() function takes three arguments: the binary string to be converted, a pointer to a size_t object to store the index of the first invalid character, and the base for conversion (in this case, 2 for binary).
- The nullptr argument is used for error handling, which means that if an invalid binary string is provided, a std::invalid_argument exception will be thrown.
- The converted number is then printed to the console.
Approach 2:Using Bitwise Operators
This approach manually converts a binary string to a number using bitwise operators.
Pros:
- Does not require any additional libraries.
- Supports leading zeros in binary strings.
- Provides low-level control over the conversion process.
Cons:
- Requires manual handling of binary string parsing and conversion.
- May not be as efficient as using standard library functions.
- Requires additional error handling for invalid binary strings.
Code:
#include <iostream>
#include <string>
int main() {
std::string binaryString = "10101"; // Binary string to be converted
int number = 0; // Initialize number to 0
int power = 1; // Initialize power of 2 to 1
// Iterate through binary string from right to left
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString[i] == '1') {
number += power; // Update number if current bit is 1
}
power <<= 1; // Shift power of 2 to the left
}
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 21
Code Explanation:
- The binary string is iterated from right to left, and each bit is checked.
- If the current bit is ‘1’, the corresponding power of 2 is added to the number variable.
- The power variable is updated by shifting it to the left by 1 bit in each iteration, which is equivalent to multiplying it by 2.
- The converted number is then printed to the console.
Approach 3: Using Standard Library Functions for String Manipulation
This approach uses string manipulation functions from the standard library to convert a binary string to a number.
Pros:
- Relies on standard library functions for string manipulation, which can be efficient and optimized.
- Provides flexibility in handling different binary string formats, such as leading zeros or spaces.
- Can handle input validation for invalid binary strings using string manipulation functions.
Cons:
- May require additional steps for parsing and conversion compared to other approaches.
- Requires careful handling of string manipulation functions to avoid potential bugs or unexpected behavior.
- May not be as efficient as using bitwise operators for binary string conversion.
Code:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string binaryString = "10110"; // Binary string to be converted
std::reverse(binaryString.begin(), binaryString.end()); // Reverse binary string for easier conversion
int number = 0; // Initialize number to 0
// Iterate through binary string and convert to integer
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString[i] == '1') {
number += (1 << i); // Update number using bitwise shift
}
}
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 22
Code Explanation:
- The binary string is reversed using the std::reverse() function from the standard library to simplify the conversion process.
- The binary string is then iterated from left to right, and each bit is checked.
- If the current bit is ‘1’, the corresponding power of 2 is added to the number variable using bitwise shift.
- The converted number is then printed to the console.
Approach 4:Using Algorithm Library
You can also use the C++ algorithm library, specifically the accumulate() function, to convert binary to a number.
Pros:
- Provides a higher-level abstraction for string manipulation and conversion.
- Relies on standard library algorithms, which are optimized and efficient.
- Can handle different binary string formats and input validation using algorithm functions.
Cons:
- Requires C++11 or later for some algorithm functions.
- May require additional steps for parsing and conversion compared to other approaches.
- May not be as efficient as using bitwise operators for binary string conversion.
Code:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string binaryString = "10010"; // Binary string to be converted
int number = 0; // Initialize number to 0
// Remove spaces from binary string
binaryString.erase(std::remove(binaryString.begin(), binaryString.end(), ' '), binaryString.end());
// Reverse binary string for easier conversion
std::reverse(binaryString.begin(), binaryString.end());
// Iterate through binary string and convert to integer
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString[i] == '1') {
number += (1 << i); // Update number using bitwise shift
}
}
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 18
Code Explanation:
- The algorithm library functions std::remove() and std::reverse() are used to remove spaces from the binary string and reverse it, respectively.
- The binary string is then iterated from left to right, and each bit is checked.
- If the current bit is ‘1’, the corresponding power of 2 is added to the number variable using bitwise shift.
- The converted number is then printed to the console.
Approach 5:Using Custom Logic
This approach uses custom logic to convert a binary string to number without relying on any standard library functions.
Pros:
- Provides flexibility in designing custom logic based on specific requirements.
- Can handle different binary string formats and input validation based on custom logic.
- May be more efficient in terms of time and space complexity compared to some standard library functions.
Cons:
- Requires careful implementation of custom logic to ensure correctness and efficiency.
- May require additional steps for parsing and conversion compared to other approaches.
- May not be as portable or reusable as standard library functions.
Code:
#include <iostream>
#include <string>
int main() {
std::string binaryString = "101110"; // Binary string to be converted
int number = 0; // Initialize number to 0
// Iterate through binary string from left to right and convert to integer
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString[i] == '1') {
number = number * 2 + 1; // Update number based on custom logic
} else if (binaryString[i] == '0') {
number *= 2; // Update number based on custom logic
} else {
std::cout << "Invalid binary string!" << std::endl; // Handle invalid input
return 1; // Return error code
}
}
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 46
Code Explanation:
- The binary string is iterated from left to right, and each bit is checked.
- If the current bit is ‘1’, the number variable is multiplied by 2 and then added 1, simulating the binary to integer conversion logic.
- If the current bit is ‘0’, the number variable is multiplied by 2, simulating the binary to integer conversion logic.
- If the current bit is neither ‘0’ nor ‘1’, an error message is displayed, and the program returns an error code.
- The converted number is then printed to the console.
Approach 6:Using Bit Manipulation
This approach uses bitwise manipulation to convert a binary string to number without relying on any standard library functions.
Pros:
- Provides direct and efficient manipulation of bits for binary string conversion.
- Can handle different binary string formats and input validation based on bitwise operations.
- Can be efficient in terms of time and space complexity compared to some other approaches.
Cons:
- Requires careful handling of bitwise operations to ensure correctness and efficiency.
- May require additional steps for parsing and conversion compared to other approaches.
- May not be as portable or readable as standard library functions.
Code:
#include <iostream>
#include <string>
int main() {
std::string binaryString = "11010"; // Binary string to be converted
int number = 0; // Initialize number to 0
// Iterate through binary string from left to right and convert to integer
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString[i] == '1') {
number |= (1 << (binaryString.length() - i - 1)); // Update number using bitwise OR and shift
} else if (binaryString[i] != '0') {
std::
cout << "Invalid binary string!" << std::endl; // Handle invalid input
return 1; // Return error code
}
}
std::cout << "Converted number: " << number << std::endl; // Output converted number
return 0;
}
Output:
Converted number: 26
Code explanation:
- The binary string is iterated from left to right, and each bit is checked.
- If the current bit is ‘1’, a bitwise OR operation is performed on the `number` variable with the result of shifting 1 by `(binaryString.length() – i – 1)` positions to the left, simulating the binary to integer conversion logic.
- If the current bit is not ‘0’ or ‘1’, an error message is displayed, and the program returns an error code.
- The converted number is then printed to the console.
Best Approach To Convert Binary To Number In C++
Here are the best qualities of the “Using C++ Standard Library Functions for String Manipulation” approach are:
- Relies on standard library functions for string manipulation, which are optimized and efficient.
- Provides flexibility in handling different binary string formats, such as leading zeros or spaces.
- Can handle input validation for invalid binary strings using string manipulation functions.
- The approach does not require any additional header files or libraries.
- Can be used for larger binary strings without overflow errors.
- The approach is platform-independent and compatible with all modern compilers.
- Suitable for applications where readability and maintainability are a priority.
Sample Problems To Convert Binary To Number In C++
Sample Problem 1:
Scenario: An engineer receives his salary in binary format, where each digit represents whether he receives a bonus for that month (1) or not (0). The engineer wants to convert the binary representation of his salary to a number in C++.
Solution Steps:
- Prompt the user to input the binary representation of an engineer’s salary using cout.
- Receive the binary salary input using cin and store it as a string variable called binarySalary.
- Convert the binary string to an integer using stoi function with the base parameter set to 2, and store the result in an integer variable called decimalSalary.
- Display the converted integer as the engineer’s salary using cout.
- Return 0 to indicate successful program execution.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Input binary representation of engineer's salary
string binarySalary;
cout << "Enter binary representation of engineer's salary: ";
cin >> binarySalary;
// Convert binary string to integer
int decimalSalary = stoi(binarySalary, 0, 2);
// Display converted integer as salary
cout << "Engineer's salary in simple number format: " << decimalSalary << endl;
return 0;
}
Output:
Enter binary representation of engineer's salary: 110110
Engineer's salary in simple number format: 54
Sample Problem 2:
Scenario: A chocolate factory produces chocolates in binary boxes, where each box is represented by a binary number. The factory manager wants to count the total number of chocolates in all the boxes and convert it to a number using C++ bitwise operators.
Solution Steps:
- Prompt the user to enter a binary representation of boxes.
- Using a for loop, iterate over each character in the input string and determine whether it represents a box with chocolates or not using an if-else statement.
- If the character is ‘1’, add one to the total number of chocolates using bitwise operators, shifting the existing total left one bit and adding one. If the character is ‘0’, shift the total left one bit without adding one.
- Print the total number of chocolates in number format.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Input binary representation of boxes
string binaryBoxes;
cout << "Enter binary representation of boxes: ";
cin >> binaryBoxes;
// Count total number of chocolates using bitwise operators
int totalChocolates = 0;
for (int i = 0; i < binaryBoxes.length(); i++) {
if (binaryBoxes[i] == '1') {
totalChocolates = (totalChocolates << 1) + 1;
} else if (binaryBoxes[i] == '0') {
totalChocolates = totalChocolates << 1;
}
}
// Display total number of chocolates in number format
cout << "Total number of chocolates: " << totalChocolates << endl;
return 0;
}
Output:
Enter binary representation of boxes: 101010
Total number of chocolates: 42
Sample Problem 3:
Scenario: A book has its page numbers represented in binary format, where each digit represents whether the page is an even page (0) or an odd page (1). The reader wants to convert the binary representation of the book’s pages to a number in C++.
Solution Steps:
- Prompt the user to input the binary representation of the book’s pages using cout.
- Read in the input as a string using cin.
- Convert the binary string to an integer using the stoi function, which takes in the binary string, a starting position of 0, and a base of 2 to indicate binary.
- Store the converted integer in a variable called decimalPages.
- Output the converted integer using cout, with an appropriate message to indicate that it represents the book’s page number.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Input binary representation of book's pages
string binaryPages;
cout << "Enter binary representation of book's pages: ";
cin >> binaryPages;
// Convert binary string to integer
int decimalPages = stoi(binaryPages, 0, 2);
// Display converted integer as book's page number
cout << "Book's page number in number format: " << decimalPages << endl;
return 0;
}
Output:
Enter binary representation of book's pages: 110010
Book's page number in number format: 50
Sample Problem 4:
Scenario: A canteen generates bills in binary format, where each digit represents whether a food item is included (1) or not included (0) in the bill. The customer wants to calculate the total amount of the bill by converting the binary representation to a number using C++ algorithm library.
Solution Steps:
- Input the binary representation of the canteen bill using the cin function and store it in a string variable called binaryBill.
- Use the accumulate function from the algorithm library to convert the binary representation of the bill into the total amount of the bill. The accumulate function takes in the binaryBill string, an initial value of 0 for the sum, and a lambda function that converts each character of the string into its corresponding number using the formula sum * 2 + (c – ‘0’).
- Store the calculated total amount of the bill in an integer variable called totalAmount.
- Output the total amount of the bill in simple number format using the cout function.
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
// Input binary representation of canteen bill
string binaryBill;
cout << "Enter binary representation of canteen bill: ";
cin >> binaryBill;
// Calculate total amount of bill using algorithm library
int totalAmount = accumulate(binaryBill.begin(), binaryBill.end(), 0,
[](int sum, char c) {
return sum * 2 + (c - '0');
});
// Display total amount of bill in simple number format
cout << "Total amount of bill: " << totalAmount << endl;
return 0;
}
Output:
Enter binary representation of canteen bill: 110101
Total amount of bill: 53
Sample Problem 5:
Scenario: A doctor writes prescriptions in binary format, where each digit represents whether a medicine is prescribed (1) or not prescribed (0) to the patient. The pharmacist wants to convert the binary representation of the doctor’s prescription to a number.
Solution Steps:
- The user is prompted to enter a binary string representing the doctor’s prescription.
- A loop iterates through each character in the binary string, and a custom logic is used to convert the binary string to a number. The logic multiplies the current value of prescription by 2 and adds the integer value of the current binary character (0 or 1) to it.
- The converted simple number, which represents the doctor’s prescription, is displayed to the user using the cout statement.
- The main function returns 0 to indicate successful execution of the program.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Input binary representation of doctor's prescription
string binaryPrescription;
cout << "Enter binary representation of doctor's prescription: ";
cin >> binaryPrescription;
// Convert binary prescription to simple number using custom logic
int prescription = 0;
for (int i = 0; i < binaryPrescription.length(); i++) {
prescription = prescription * 2 + (binaryPrescription[i] - '0');
}
// Display converted simple number as doctor's prescription
cout << "Doctor's prescription in simple number format: " << prescription
<< endl;
return 0;
}
Output:
Enter binary representation of doctor's prescription: 101001
Doctor's prescription in simple number format: 41
Sample Problem 6:
Scenario: A salesperson generates sales reports in binary format, where each digit represents whether a sale is made (1) or not made (0) for a particular item. The manager wants to calculate the total number of sales made by converting the binary representation to a number using C++ bit manipulation.
Solution Steps:
- The program prompts the user to enter a binary representation of a sales report.
- The program iterates through each character in the binary sales report string, and for each character, it performs a bitwise left shift operation on the totalSales variable (which is initialized as 0), followed by a bitwise OR operation with the result of subtracting ‘0’ from the binary character. This converts the binary string to an integer using bit manipulation.
- The program displays the total number of sales made by outputting the value stored in the totalSales variable after the binary conversion, in a simple number format.
- The program returns 0 to indicate successful completion and termination of the program.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Input binary representation of sales report
string binarySalesReport;
cout << "Enter binary representation of sales report: ";
getline(cin, binarySalesReport);
// Convert binary sales report to simple number using bit manipulation
int totalSales = 0;
for (int i = 0; i < binarySalesReport.length(); i++) {
totalSales = (totalSales << 1) | (binarySalesReport[i] - '0');
}
// Display total number of sales made in simple number format
cout << "Total number of sales made: " << totalSales << endl;
return 0;
}
Output:
Enter binary representation of sales report: 110101
Total number of sales made: 53
Conclusion:
In this blog, we explored six different ways to perform this task: Using Standard Library Functions,Using Bitwise Operators,Using Standard Library Functions for String Manipulation,Using Algorithm Library,Using Custom Logic and Using Bit Manipulation.
Using Standard Library Functions for String Manipulation is the best approach among all of them. It’s easy to use and flexible.It is important to choose the appropriate method which depends as per the need of the project.