C++ int type Binary Literals

Introduction

You create a binary integer literal as binary digits (0 or 1) prefixed by 0b or 0B.

A binary literal can have L or LL as a suffix to indicate it is type long or long long, and u or U if it is an unsigned literal. For example:

0B110101111      0b100100011U         0b1010L  0B11001101         0b11111111
#include <iostream>

int main()//from  w ww  .  j  a v a2  s .c  om
{
    int color {0b000011110000110100001110};

    std::cout << "The value of color is "  << color  << std::endl;
}

Values are represented by literals.

So far, we have mentioned three different kinds of binary literals: decimal, hexadecimal, and octal as in the example below:

int main() 
{ 
    int x = 10; 
    int y = 0xA; 
    int z = 012; 
} 

These three variables have the same value of 10, represented by different number literals.

C++14 standard introduces the fourth kind of integral literals called binary literals.

Using binary literals, we can represent the value in its binary form.

The literal has a 0b prefix, followed by a sequence of ones and zeros representing a value.

To represent the number 10 as a binary literal, we write:

int main() 
{ 
    int x = 0b101010; 
} 

The famous number 42 in binary form would be:


int main() 
{ 
    int x = 0b1010; 
} 

Values are values; they are some sequence of bits and bytes in memory.

What can be different is the value representation.

there are decimal, hexadecimal, octal, and binary representations of the value.

these different forms of the same thing can be relevant to us humans.to a machine, it is all bits and bytes, transistors, and electrical current.




PreviousNext

Related