I am frequently wishing I could do something like this in C:
val1 &= 0b00001111; // Clear high nibble
val2 |= 0b01000000; // Set bit 7
val3 &= ~0b00010000; // Clear bit 5
Having this syntax seems like an incredibly useful addition to C without any downsides that I can think of, and it seems like a natural thing for a low-level language where bit twiddling is fairly common.
I'm seeing some other great alternatives, but they all fall apart when there is a more complex mask. For example, if reg
is a register that controls I/O pins on a microcontroller, and I want to set pins 2, 3, and 7 high at the same time I could write reg = 0x46;
, but I had to spend 10 seconds thinking about it (and I'll likely have to spend 10 seconds again every time I read that code after not looking at it for a day or two).
Or I could write reg = (1 << 1) | (1 << 2) | (1 << 6);
, but personally I think that is way less clear than just writing `reg = 0b01000110;'. I can agree that it doesn't scale well beyond 8-bit or maybe 16-bit architectures though. Not that I've ever needed to make a 32-bit mask.
Looks like C23 now has binary literals.