# 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.

```int i1 = 42;
int i2 = 052;
int i3 = 0x2A;
int i4 = 0b101010;
```

Binary literals can be used anywhere integral literals are expected.

```enum class flags
{
write    = 0b0010,
execute  = 0b0100
};```

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:

```int n1 = 0b1011'1100'0110'0001'0100'1110;
int n2 = 0b10111100'01100001'01001110;```

`int n3 = 0xbc'61'4e;`

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).

```int n1 = 12345;
int n2 = 1'2'3'4'5;
int n3 = 1'23'4'5;
int n4 = 1'234'5;
int n5 = 12'3'45;
int n6 = 12'345;
```

### 6 thoughts on “Binary literals and digit separators”

1. “can’t leave without” -> “can’t live without” ?

• I’ve fixed the typo. Thank you for pointing it!

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

3. 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.