Reputation: 343
I need help with finding the correct bit mask. 0xbc61 has to be 0xbcaa, but I am not sure how to create the bit mask to affect only the part I have to change. I also tried splitting the value but wasn't sure how to "glue" them with the new one...
unsigned short int left, right;
unsigned short int temp = 0xbc61;
unsigned short int newValue = 0xaa;
right= temp & 0xff; // split
left= (temp >> 8) // split
// temp needs to be 0xbcaa
// and I also need it the other way round, so 0xbc61 -> 0xaa61
Upvotes: 0
Views: 1561
Reputation: 68004
to change any arbitraty bits to anothers:
uint32_t changebits(uint32_t val, uint32_t mask, uint32_t newvalue)
{
val &= ~mask;
val |= (newvalue & mask);
return val
}
changebits(0xe323da98, 0b00000110011000010100000100000000, 0xde45ab67);
it will set only the bits given by the second parameters to the same bits from the third parameter.
in your case
changebits(0xbc61, 0xff, 0xaa);
Upvotes: 1
Reputation: 6875
You can use the XOR
here:
0x61
is 0b01100001
0xaa
is 0b10101010
To convert one value into another just use XOR
with 0xCB
(0b11001011
):
unsigned short mask = 0xbc61;
....
// convert to new mask 0xbcaa
mask ^= 0xCB; // mask now is 0xbcaa
...
// convert back to 0xbc61
mask ^= 0xCB; // mask now is 0xbc61
NOTE: A XOR 1 = !A
and A XOR 0 = A
Here is the demo: https://ideone.com/UIxPDV
Upvotes: 1
Reputation: 101
You mean newValue = (oldValue & 0xff00) | 0xaa;
? Or you need to use minimal mask? If so, write your number in binary and check it. :)
Upvotes: 0