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 with no downsides that I can think of, and it seems like a natural thing for a low level language where bit-twiddling is fairly common.
Edit: 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 those code after a 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.
C has "binary" literals, but only 2 of them: 0, 1. ;-) For what it's worth, C++14 will have these.
In C, you can express integers using their binary or hexadecimal representations by prefixing them with 0b or 0x .
A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value.
6.65 Binary Constants using the ' 0b ' Prefix Integer constants can be written as binary constants, consisting of a sequence of ' 0 ' and ' 1 ' digits, prefixed by ' 0b ' or ' 0B '. This is particularly useful in environments that operate a lot on the bit level (like microcontrollers).
According to Rationale for International Standard - Programming Languages C §6.4.4.1 Integer constants
A proposal to add binary constants was rejected due to lack of precedent and insufficient utility.
It's not in standard C, but GCC supports it as an extension, prefixed by 0b
or 0B
:
i = 0b101010;
See here for detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With