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?
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.
binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits ( 0 , 1 )
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.
C has "binary" literals, but only 2 of them: 0, 1. ;-) For what it's worth, C++14 will have these.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With