Search This Blog

Loading...

09 July 2009

Binary Literals

I was randomly browsing for some stuff and I stumbled across this post on binary literals. It proposed the following as an option for C++ which the article admits as being inefficient:
unsigned long const mask
= std::bitset<6>(std::string("111100")).to_ulong();


I was thinking that C++ templates must be able to offer something more efficient...
template <int N>
struct Binary
{
enum { value = Binary<N % 10> | 2 * Binary<N / 10>::value }
};

template<>
struct Binary<0>
{
enum { value = 0; }
};

template<>
struct Binary<1>
{
enum { value = 1; }
}

int foo = Binary<111100>::value;


Usual caveats apply. Code is untested and may eat kittens.
Post a Comment