C++14 binary literals and digit separator


C++14 augmented C++(and C++11) with many features.The
i)Binary literals and
ii)Digits separators
are two features added in C++14.

Binary literals

When writing programs which involve mathematical evaluations or program involving various types of number we usually like to specify each digit type with their specific prefixes.Say to specify a hexadecimal digit we will use the prefix ‘0x‘ and to specify an octal type we will use the prefix ‘0‘.Like wise if we wish to assign a binary digits directly to a variable we will use the prefix ‘0b‘ or ‘0B‘,either of them work fine.And note here you will be assigning a binary digits which means you will be using only 1 and 0 to represent the number.

Code example

auto hex=0x12ab; ///hexadecimal number

auto octal=0127 ; //octal number

auto binary=0b10001000 ; //binary digit

auto bin=0B0123; //error

cout<< hex << endl
<< octal << endl
<< binary ;

Output

4779
87
136

In the output the the binary digit 10001000 is converted to decimal type using the base-2 numeral system.Hence we get ‘binary’ value as 136.





Digit separation

Prior to C++14 there was no way to separate digits of a number in numeric literals.But with C++14 a single-quote character may be used to separate the digits within a number.The only advantage of using digit separator is better readability of a number consisting of many digits.

Code example

auto million=1000000 , ///A million,not so obvious to the eye
Million=1000’0000 ; ///definitely obvious to the eye

auto B16=0b1000’0000’0000’0000 , ///easier to grasp the number of bits
b16=0B1000000000000000 ; ///harder to guess the number of bits