Consider the following:
#include <iostream>
int main()
{
int bin {};
bin = 0b0011; // Assign binary 3 to the variable
std::cout << bin << '\\n' // Prints decimal 3
bin = 0b1100;
std::cout << bin << '\\n'; // Prints decimal 12
}
// Terminal
3
12
Hey! What happened?
We assigned binary values to the variable however std::cout printed their decimal representation.
C++ allows us to initialize a variable with any numbering system
int a { 12 };
int b { 0b1100 };
int c { 0xC };
All of these values are equivalent. However, the variable doesn’t record if its decimal, hexadecimal, binary or octal.
How std::cout behaves
std::cout defaults to printing decimal. It can be formatted to support other number systems via std::hex, std::oct. However, it doesn’t support the binary system.
Aah. Printing binary is more cumbersome
The solution is to use <bitset>.
The program below prints numbers which are of type std::bitset. A helper function is used to add whitespace for long binary numbers. This is to enhance readability as 1100111001010001 is quite difficult to discern.
#include <iostream>
#include <bitset>
#include <string>
std::string addNibbleSpacing(std::string bits)
{
std::string formatted{};
for (std::size_t i{0}; i < bits.length(); ++i)
{
formatted += bits[i];
if ((i + 1) % 4 == 0 && i + 1 != bits.length())
{
formatted += ' ';
}
}
return formatted;
}
int main()
{
std::bitset<8> b1 { 0b1101'0010 };
std::bitset<16> b2 { 0b1100'1110'0101'0001 };
std::cout << "The binary values are:\\n";
std::cout << "8-bit value: " << addNibbleSpacing(b1.to_string()) << '\\n';
std::cout << "16-bit value: " << addNibbleSpacing(b2.to_string()) << '\\n';
}
// Output
The binary values are:
8-bit value: 1101 0010
16-bit value: 1100 1110 0101 0001