You’d think I’d know this stuff by now.
Thursday, February 12th, 2009I’ve been using C and C++ for about ten years now, both personally and professionally. And yet, I’ve never encountered a specific bit of syntax that I really should already know about: bit fields. You can specify the specific number of bits required for integer members of C structs, allowing the compiler to take care of the bit masking and marshalling for you:
typedef struct foo {
unsigned int flag_0 : 1, // one-bit variable (0..1)
unsigned int small_enum : 4, // four-bit variable (0..15)
unsigned int other_index : 3, // three-bit variable (0..7)
} foo;
This struct will be packed into a single byte (actually probably a single int), which can potentially save quite a bit of space. You could do the same thing manually by specifiying one “flags” field and doing the bit-twiddling on your own, but the bit fields make the meaning and the code a lot cleaner.
I’m embarrassed to admit that I didn’t know this even existed until yesterday, when I had to open up the NSWindow sources to look something up.