mTesseracted
mTesseracted

Reputation: 290

Calc number of bits needed to represent a value using TMP

I want to use template meta programming to calculate the minimum number of bits I need to represent a given number. I've never used TMP before so that's probably what have is completely laughable.

struct ValueHolder
{
   typedef float value;
};

template<struct ValueHolder>
struct logB2
{
   enum { result = (((*(int*)&ValueHolder.value & 0x7f800000) >> 23) - 127) };
};

template <struct logB2 n>
struct bits2use {

    enum { return = !((n::return > 0) && !(n::return & (n::return-1))) ? n++ : n };
};

#ifndef NUM 
#define NUM 18 
#endif

int main()
{
   std::cout << bits2use<NUM>::return << '\n';
   return 0;
}

Here's what my run time code that I know works looks like:

int ch_bits;                    //how many bits needed to send the channel
float xf = CHN_CNT;             //need a float for log2 calc
int x = CHN_CNT;

//Calculate how many bits you need for a given integer, i.e. for a 64 channels you need
//6 bits to represent 0-63 unsigned.
ch_bits = ((*(int*)&xf & 0x7f800000) >> 23) - 127;  //log_2
if( !((x > 0) && !(x & (x-1))) )                    //true if x is not a power of 2
    ch_bits ++;

Upvotes: 3

Views: 196

Answers (1)

6502
6502

Reputation: 114559

This should do what you're looking for

#include <stdio.h>

template<int N> struct bits;
template<> struct bits<1> { enum { value=1 }; };
template<int N> struct bits { enum { value = 1 + bits<(N>>1)>::value }; };

int main() {
    printf("%i\n", bits<5000>::value);
    return 0;
}

Upvotes: 1

Related Questions