UUD

UUD

0p

1 comments posted · 0 followers · following 0

10 years ago @ Preshing on Programming - Safe Bitfields in C · 0 replies · +5 points

I have a usecase that requires more than 64 bits of storage (array of 8 elements with 5 bits each, plus an array of 9 elements of 4 bits each). I have cobbled together the following template to enable >64bits of storage. Haven't tested the code yet, but it already compiles when using only the ADD_BITFIELD_MEMBER macro. It doesn't compile yet when using ADD_BITFIELD_ARRAY, but that is not why I post here.

My reason for posting here is to find out whether this approach can be made feasible with your bitfield class while retaining its nice "no undefined behaviour" property. As you can see, the idea is to pass a user-defined type to your macro to overcome the 64 bit limitation. I think this could be a useful addition and I'd like to hear your opinion on this!

// wrapper around static array to enable bitfields with >64 bits
template<size_t NUM_CHARS>
struct CharArrayWrapper
{
uint8_t data[NUM_CHARS];
CharArrayWrapper(int x){ data = {x}; }; // need this to avoid compile error in bitfield.h
CharArrayWrapper& operator=(int x) { };
};

BEGIN_BITFIELD_TYPE(SomeLargeStruct, CharArrayWrapper<10>)
ADD_BITFIELD_ARRAY(eight_times_5, 0, 5, 8)
ADD_BITFIELD_ARRAY(nine_times_four, 40, 4, 9)
ADD_BITFIELD_MEMBER(four_bits_padding, 76, 4)
END_BITFIELD_TYPE()