Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Binary literal in C++

📅 2014-Sep-10 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ binary literal, cpp ⬩ 📚 Archive

C++ has always had support for specifying integer values in the form of decimal literals (like 255), hexadecimal literals (like 0xFF) or octal literals (like 0377).

C++14 has added support for specifying integer values using binary literals. This makes code using binary or performing bit manipulation easier to write, understand and fix. Binary literals can be specified using the prefix of 0b or 0B.

int i = 0b0011;
int j = 0B01101001;

I found that this was supported in GCC 5.1 compiler when the code was compiled with the -std=c++11 flag.

Additionally, C++14 also adds support for digit separator character, which is the single quote character. This can be added anywhere among the bits to help separate them for easier understanding.

int k = 0B0101'0111'1100;

I found this was not yet supported in GCC 5.1.