I'd write two lines to set, say, some bits to something. Here, for example, I want to set upper 8 bits in uint16_t value x to y's lower 8 bits.
uint16_t y = 0x0034;
uint16_t x = 0xFF12;
I want to have x:
assert(x == 0x3412);
I tend to write these two lines:
x &= 0x00FF;
x |= (y << 8);
Is there a way of writing a single line to achieve the same effect without using macro?
How to set, clear or toggle a single bit in C/C++? Bitwise Operators are mainly used in low-level programming. Using the bit-wise operators we can set bit, check bit, clear or toggle the bits of an integral type. In the embedded system, a bit-wise operator performs the bit-wise operation on an individual bit of a PORT or Register.
Any bit <bitwise OR> Set bit = Set bit which means, 0 | 1 = 1 1 | 1 = 1 So for setting a bit, performing a bitwise OR of the number with a set bit is the best idea. N = N | 1 << K OR N |= 1 << K where K is the bit that is to be set
Set, toggle and clear a bit in C 1 Setting a bit. Use the bitwise OR operator ( |) to set a bit. That will set a bit x. 2 Clearing a bit. Use the bitwise AND operator ( &) to clear a bit. That will clear bit x. ... 3 Toggling a bit. The XOR operator ( ^) can be used to toggle a bit. That will toggle bit x. That’s it, hope it helps.
In C, bitwise OR operator ( |) used to set a bit of integral data type. As we know that | (Bitwise OR operator) evaluates a new integral value in which each bit position is 1 only when operand’s (integer type) has a 1 in that position.
Just expand out the two lines:
x &= 0x00FF; // x = x & 0xFF
x |= (y<<8); // x = x | (y<<8)
// and combine
x = (x & 0xFF) | (y << 8);
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