/// Implementation use by the Macro VALUE_TO_NB_BITS(x)
template<unsigned N struct NbBits
{
enum
{
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;
} |