This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  C++ Compile-Time Binary Constants
  Submitted by



C++ doesn't allow declaring binary constants ( 0b11001 would have been nice !) So, I tried to fix that using template recursion & partial specialization.

Note that, because you actually declare int's, you are limited to use only 10 digits (so the max is 1023)

The code should be self-explanatory !
Hope it's useful to someone !

Predator 2003

template<long int N
class binary
{
        public:
                enum {
                        bit = N % 10,
                        value = bit + (binary<N/10::value << 1)
                };
};

class binary<0 { public: enum { bit = 0, value = 0 }; };

// // Examples // #include <stdio.h

void main() { printf("9 = %i\n255 = %i\n37351 = %i\n16843009 = %li\n",

binary<1001::value, //this compiles to "push 9" for example

binary<11111111::value,

binary<11100111::value | binary<10010001::value << 8, //you can live with this binary<1::value | binary<1::value<<8 | binary<1::value<<16 | binary<1::value<<24 //kinda overkill, I know !

); }



The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.