Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary literals?

Tags:

c++

In code, I sometimes see people specify constants in hex format like this:

const int has_nukes        = 0x0001; const int has_bio_weapons  = 0x0002; const int has_chem_weapons = 0x0004; // ... int arsenal = has_nukes | has_bio_weapons | has_chem_weapons; // all of them if(arsenal &= has_bio_weapons){   std::cout << "BIO!!" } 

But it doesn't make sense to me to use the hex format here. Is there a way to do it directly in binary? Something like this:

const int has_nukes        = 0b00000000000000000000000000000001; const int has_bio_weapons  = 0b00000000000000000000000000000010; const int has_chem_weapons = 0b00000000000000000000000000000100; // ... 

I know the C/C++ compilers won't compile this, but there must be a workaround? Is it possible in other languages like Java?

like image 926
Frank Avatar asked Feb 11 '09 15:02

Frank


People also ask

What are binary literals?

A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value.

What are binary literals in C++?

binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits ( 0 , 1 )

What is binary literal in Python?

Binary literals begin with a leading 0b or 0B, followed by binary digits (0-1). All of these literals produce integer objects in program code; they are just alternative syntax for specifying values. The built-in calls hex(I), oct(I), and bin(I) convert an integer to its representation string.

Does C have binary literals?

C has "binary" literals, but only 2 of them: 0, 1. ;-) For what it's worth, C++14 will have these.


1 Answers

In C++14 you will be able to use binary literals with the following syntax:

0b010101010 /* more zeros and ones */ 

This feature is already implemented in the latest clang and gcc. You can try it if you run those compilers with -std=c++1y option.

like image 187
sasha.sochka Avatar answered Oct 15 '22 01:10

sasha.sochka