Binary literals?

Solution 1:

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.

Solution 2:

I'd use a bit shift operator:

const int has_nukes        = 1<<0;
const int has_bio_weapons  = 1<<1;
const int has_chem_weapons = 1<<2;
// ...
int dangerous_mask = has_nukes | has_bio_weapons | has_chem_weapons;
bool is_dangerous = (country->flags & dangerous_mask) == dangerous_mask;

It is even better than flood of 0's.

Solution 3:

By the way, the next C++ version will support user defined literals. They are already included into the working draft. This allows that sort of stuff (let's hope i don't have too many errors in it):

template<char... digits>
constexpr int operator "" _b() {
    return conv2bin<digits...>::value;
}

int main() {
    int const v = 110110110_b;
}

conv2bin would be a template like this:

template<char... digits>
struct conv2bin;

template<char high, char... digits>
struct conv2bin<high, digits...> {
    static_assert(high == '0' || high == '1', "no bin num!");
    static int const value = (high - '0') * (1 << sizeof...(digits)) + 
                             conv2bin<digits...>::value;
};

template<char high>
struct conv2bin<high> {
    static_assert(high == '0' || high == '1', "no bin num!");
    static int const value = (high - '0');
};

Well, what we get are binary literals that evaluate fully at compile time already, because of the "constexpr" above. The above uses a hard-coded int return type. I think one could even make it depend on the length of the binary string. It's using the following features, for anyone interested:

  • Generalized Constant Expressions.
  • Variadic Templates. A brief introduction can be found here
  • Static Assertions (static_assert)
  • User defined Literals

Actually, current GCC trunk already implements variadic templates and static assertions. Let's hope it will support the other two soon. I think C++1x will rock the house.

Solution 4:

The C++ Standard Library is your friend:

#include <bitset>

const std::bitset <32> has_nukes( "00000000000000000000000000000001" );

Solution 5:

GCC supports binary constants as an extension since 4.3. See the announcement (look at the section "New Languages and Language specific improvements").