I have two unsigned int numbers: a
and b
(b is an unsigned int pointer). I want to copy 8th and 9th bit of a
to 2nd and 3rd bit of b
(all indices are 0 based).
This is how I am doing it:
bool secondBit = (a & (1 << 8) ) ;
bool thirdBit = (a & (1 << 9) ) ;
if (secondBit) {
*b |= (1u << 2);
}
if (thirdBit) {
*b |= (1u << 3);
Reminder: b
is an unsigned int pointer.
Is there a better way of doing this ?
Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both.
Clear the relevant bits of *b
and set them to the bits you want from a
:
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
// This is the 'not' of 00001100, in other words, 11110011
~0xC;
// This zeros the bits of *b that you do not want (b being a pointer)
*b & ~0xC; // *b & 11110011
//This clears all of a except the bits that you want
a & 0x300;
// Shift the result into the location that you want to set in *b (bits 2 and 3)
((a & 0x300) >> 6);
// Now set the bits into *b without changing any other bits in *b
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
Depends on your definition of "better" :)
But, well, there is the std::bitset
class in C++. Perhaps it suits your needs by offering a less error-prone interface.
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