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.


  Bits Needed To Store A Value At Compile-time
  Submitted by

Whether you're using bit vectors, manipulating flags or doing some assertions, you might need to know how many bits are needed to store an integer value. This tip will do the job for you at compilation time thanks to template metaprogramming as described in Game Programming Gems 1. It uses a recursive call to NbBits<(x)> to reduce VALUE_TO_NB_BITS(x) to a constant. Compile-time and readability penalities are insignificant compared with execution time and extensibility benefits...

Etranges Team

/// Implementation use by the Macro VALUE_TO_NB_BITS(x)
template<unsigned N struct NbBits
                Val =  1 + NbBits< (N  1) ::Val 

/// End of recursive calls template< struct NbBits<0 { enum

{ Val = 0 }; };

/// Macro which compute number of bits to store value 'x' #define VALUE_TO_NB_BITS(x) ( NbBits<(x)::Val )

/// Sample enum { VALUE0, VALUE1, VALUE2, VALUE3, VALUE4, VALUE5, NB_VALUES };

#include <stdio.h #include <stdlib.h

/// Main int main() { printf("%d-%d bits, %d-%d bits, %d-%d bits %d-%d bits\n", 3, VALUE_TO_NB_BITS(3), 4, VALUE_TO_NB_BITS(4), 50, VALUE_TO_NB_BITS(50), NB_VALUES-1, VALUE_TO_NB_BITS(NB_VALUES-1) ); // Output : // 3-2 bits, 4-3 bits, 50-6 bits 5-3 bits return 0; }

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.