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.


C++14 Binary literals

When writing programs which involve mathematical evaluations or various types of number, we usually like to specify each digit type with specific prefix. Say to specify a hexadecimal digit, we will use the prefix ‘0x‘ and to specify the octal type we will use the prefix ‘0‘. Like wise if we wish to assign a binary digit directly to a variable, we will use the prefix ‘0b‘ or ‘0B‘, either of them work fine. Note to assign a binary digit you will have to use only 1 and 0 in the initializer.

auto hex=0x12ab; ///hexadecimal number

auto octal=0127 ; //octal number

auto binary=0b10001000 ; //binary digit

auto bin=0B0123; //error! cannot use anything besides 1 or 0

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

Output

4779
87
136

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


C++14 Digit separation

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

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 guess the number 
b16=0B1000000000000000 ; //harder to guess the number of bits



Leave a Reply

Your email address will not be published. Required fields are marked *