Binary literals in C++

In C++, binary literals allow you to represent numbers in their binary form directly in your code. This feature was introduced in C++14. It can be quite useful when dealing with bit manipulations or working with binary-based data.

To specify a binary literal, you can use the prefix 0b or 0B, followed by a sequence of 0s and 1s.

Here’s an example of how you can use binary literals in C++:

#include <iostream>

int main() {
    int binaryNumber = 0b1010101;  // binary literal representing 85
    std::cout << binaryNumber << std::endl;

    return 0;
}

In this example, 0b1010101 represents the binary value of 85. The program will output 85 when executed.

Binary literals can also be combined with other number prefixes, such as 0x for hexadecimal or 0 for octal, to facilitate different numeric representations within the code.

Here’s another example that demonstrates the combination of binary, hexadecimal, and octal literals:

#include <iostream>

int main() {
    int binaryNumber = 0b1010101;   // binary literal representing 85
    int hexadecimalNumber = 0x2A;   // hexadecimal literal representing 42
    int octalNumber = 052;          // octal literal representing 42

    std::cout << binaryNumber << std::endl;
    std::cout << hexadecimalNumber << std::endl;
    std::cout << octalNumber << std::endl;

    return 0;
}

In this example, binaryNumber is set to the binary literal 0b1010101 which represents 85. hexadecimalNumber is set to the hexadecimal literal 0x2A which represents 42. octalNumber is set to the octal literal 052 which also represents 42. The program will output:

85
42
42

Binary literals provide a convenient way to represent binary values directly in the code, making it easier to work with and understand binary-based operations. They can be particularly useful when dealing with low-level programming or tasks that involve bit manipulation.

Keep in mind that support for binary literals may vary depending on the compiler and C++ standard used. It is always a good practice to check the compatibility of your code with different compilers and versions.

References: