Binary Literals
C++14 introduced binary literals, making it easier and more intuitive to represent binary numbers directly in code.
This is particularly useful for situations requiring bitwise operations or bitmasking using binary representation.
By simply adding 0B or 0b before a numerical value, it helps others understand that binary notation is being used, eliminating the need to manually convert it from decimal to binary.
Let’s look at some code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Function to print the binary representation of an integer value
template <typename T>
void printBinary(T num) {
const int bits = sizeof(num) * 8; // Calculate the number of bits in the integer
for (int i = bits - 1; i >= 0; --i) {
std::cout << ((num >> i) & 1); // Extract each bit and print it
}
std::cout << std::endl;
}
int main() {
// Using binary literals to represent decimal numbers
int num1 = 0b101010; // Binary representation of 42
int num2 = 0b11110000; // Binary representation of 240
std::cout << "Decimal value of num1: " << num1 << std::endl; // Output: 42
printBinary(num1);
std::cout << "shift right 1 bit: " << std::endl;
num1 = num1 >> 1;
printBinary(num1);
std::cout << "-------------" << std::endl;
std::cout << "Decimal value of num2: " << num2 << std::endl; // Output: 240
printBinary(num2);
std::cout << "shift right 1 bit: " << std::endl;
num2 = num2 >> 1;
printBinary(num2);
return 0;
}
Result