I have a 5 byte data element and I need some help in figuring out how in C++ to set an individual bit of one of these byte; Please see my sample code below:
char m_TxBuf[4];
I would like to set bit 2 to high of byte m_TxBuf[1]
.
00000 0 00 ^ This one
Any support is greatly appreciated; Thanks!
Typically we set bits using bitwise operator OR (operator| or operator|= as a shorthand).
Assuming 8-bits to a byte (where the MSB is considered the '7st' bit and the LSB considered the 0th: MSB 0) for simplicity:
We can write a simple function:
We can likewise test bits using operator&.
You should also consider std::bitset for this purpose which will make your life easier.
To set a bit, you use bitwise or. The above uses compound assignment, which means the left side is one of the inputs and the output.
Bitwise operators in C++.
Bit endianness.
m_TxBuf[1] |= 1 << 2
Just use std::bitset<40> and then index bits directly.
You can use bitwise-or (
|
) to set individual bits, and bitwise-and (&
) to clear them.