Because layout of bit fields is implementation-dependent I am looking for alternative to C struct. wikipedia suggests to emulate bit fields with bit operators.
Let's assume we have incoming integer variable with unknown value (range 0-7). Before the value can be set as WIDTH it must be shifted var << 2
according to it's bit field declaration. Furthermore to ensure variable out of range is not overlapping foreign bits var &= ~224
must deleted from left.
#define BOLD 0b00000001
#define ITALIC 0b00000010
#define WIDTH 0b00011100
#define HEIGHT 0b11100000
unsigned char flagword = 0;
unsigned int intvar = 7;
How can we determine unknown shift count of previous declared variable bit masks?
How to cast integer into desired bit position with C style bit shift or C++ std::bitset?
// desired function C/C++
void setBit( unsigned char * byte, unsigned char bitmask, unsigned int value ) {
unsigned char bitfield = *byte;
if ( value ) {
/* determine shift count from bitmask
cast + shift int
set bits
*/
bitfield |= bitmask;
}
else
// delete bits
bitfield &= ~bitmask;
*byte = bitfield;
}
// desired function call
setBit( &flagword, WIDTH, intvar );
Note: This is not a homework