A
Andy Venikov
Sometimes you want to use a bitfield to hold an enum value. In such
cases you would only use as many bits as are needed to encode the
full set of enum values. And it is a pain to recompute and updated
the bitfield length each time you add new enum values. But there is
a way to make the compiler do it for you. Like this:
enum Enums
{
Enum1,
Enum2,
Enum3,
Enum4,
TotalEnums,
};
struct A
{
Enums enumValue:COMPUTE_BITFIELD_LENGTH(TotalEnums);
};
And COMPUTE_BITFIELD_LENGTH would look something like this:
#define COMPUTE_BITFIELD_LENGTH(n) ((n) < 1) ? 0 : ((n) < 3) ? 1 :\
((n) < 5) ? 2 : ((n) < 9) ? 3 : ((n) < 17) ? 4 : ((n) < 33) ? 5 :\
((n) < 65) ? 6 : ((n) < 129) ? 7 : ((n) < 257) ? 8 : 32
It works fine.
Unless the number Enums is exactly the power of 2, in wich case
some compilers give warning akin to this:
"A::enumValue is too small to hold all values of Enums" appears.
It happens because the compiler considers TotalEnums to be part of the
enum set in wich case the total number of values become power of 2 plus
one and you need one additional bit.
Is there a way to compute the size of the enum structure
without introducing a new enum value?
Thanks,
Andy.
cases you would only use as many bits as are needed to encode the
full set of enum values. And it is a pain to recompute and updated
the bitfield length each time you add new enum values. But there is
a way to make the compiler do it for you. Like this:
enum Enums
{
Enum1,
Enum2,
Enum3,
Enum4,
TotalEnums,
};
struct A
{
Enums enumValue:COMPUTE_BITFIELD_LENGTH(TotalEnums);
};
And COMPUTE_BITFIELD_LENGTH would look something like this:
#define COMPUTE_BITFIELD_LENGTH(n) ((n) < 1) ? 0 : ((n) < 3) ? 1 :\
((n) < 5) ? 2 : ((n) < 9) ? 3 : ((n) < 17) ? 4 : ((n) < 33) ? 5 :\
((n) < 65) ? 6 : ((n) < 129) ? 7 : ((n) < 257) ? 8 : 32
It works fine.
Unless the number Enums is exactly the power of 2, in wich case
some compilers give warning akin to this:
"A::enumValue is too small to hold all values of Enums" appears.
It happens because the compiler considers TotalEnums to be part of the
enum set in wich case the total number of values become power of 2 plus
one and you need one additional bit.
Is there a way to compute the size of the enum structure
without introducing a new enum value?
Thanks,
Andy.