Learn How To Use Binary Literals In Modern C++
C++14 brings us fewer but useful features to modern C++ than the standards preceding it. The creator of C++, Bjarne Stroustrup says that improvements in C++14 were deliberately lower in quantity compared to C++11. One of the small but useful features is the introduction of “Binary Literals”. C++14 comes with the Binary Literals feature, and in this post, we explain how we can use binary bits.
Learn how to use binary literals in modern C++
A binary literal is an integer literal that your binary number begins with 0b
or 0B
and consists of a sequence of binary digits (base two). It is defined in
and provides a convenient way to represent a binary base-2 number (1 and 0), useful for the developers in IDE, and useful to compilers that understand it is a binary value.
Here is a simple example of how we can use it.
#include
int main(){ int b1 = 0b00111011; }
|
Is there a simple example about how to use binary literals in modern C++?
We can use it with digital separators, which are another feature of C++. Here is an example, this time we used constants.
const int b8 = 0b1111‘0000; const int b16 = 0b1111′0000‘1111’0000; const int b32 = 0b1111‘0000’1111‘0000’1111‘0000’1111‘0000;
|
Note that, we can NOT use digital separator after the 0b
literal as below.
const int b8 = 0b‘1111’0000;
|
Is there a full example about how to use binary literals in modern C++?
Here is a full example about how to use binary literals in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include #include
int main() { int b = 0b00111011;
int b8 = 0b1111‘0000; int b16 = 0b1111′0000‘1111’0000; int b32 = 0b1111‘0000’1111‘0000’1111‘0000’1111‘0000;
std::cout << std::bitset<8>(b8) << std::endl; std::cout << std::bitset<16>(b16) << std::endl; std::cout << std::bitset<32>(b32) << std::endl;
system(“pause”); return 0;
}
|
11110000 1111000011110000 11110000111100001111000011110000
|
For more details about the binary literals, please see https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.