Binary literals and digit separators

The C++14 standard provides two new small features to the language: binary literals and digit separators. They are already available in Clang 3.4 and GCC 4.9 and now Visual Studio 2015 RC has implemented them. They may not be something you can’t live without, but sometimes it’s convenient to have them. Let’s have a look.

In C++ it was possible to input integer literals in several bases: decimal, hexadecimal and octal. However, the binary base has been omitted (though other languages supported that). With C++14 binary is also supported and binary literals are introduced with the prefix 0b or 0B.

Binary literals can be used anywhere integral literals are expected.

What if you had to write large literals such as 0b101111000110000101001110, which is the binary representation of decimal 12345678? Sometimes it is convenient to separate groups of digits for more human readability.

C++14 defines the single quotation mark (') as a digit separator in integral and floating point literals. So the binary literal 0b101111000110000101001110 can be expressed in several ways:

or maybe in hexadecimal:

The position of the single quotation marks in the integral or floating point literals is irrelevant, they are simply ignored when determining the value of the literal. All the following are equivalent (but probably only the first and the last make sense).

6 thoughts on “Binary literals and digit separators

  1. simmo

    In binary literals the separators might actually make sense to indicate different sections of bit packed data though.

    Reply
  2. Syamala Tadigadapa

    Perl supports the underscore character as a digit separator. To me,

    int n1 = 0b1011_1100_0110_0001_0100_1110;

    appears far more nicer to eye than

    int n1 = 0b1011’1100’0110’0001’0100’1110;

    Fundamental objection to the quote character as a digit separator is that it (the quote) has another well defined role to play in the language. The under score looks more natural as it is always associated with digits and letters. Here using it a digit separator does not cause any surprise to the reader as it does not impart any unnatural duty to the said underscore character. Another reason why we would prefer an underscore to the quote is that the underscore is wider in space occupation on the real-estate to the quote which is hard to see, particularly in print.

    Reply
    1. Ivan

      Underscores are used for user-defined literals, and it would lead to ambiguities in the language. (they were considered)

      Reply

Leave a Reply