I have a strange problem in C++, I’m sure I’m missing something obvious but cannot figure out what.
The purpose of the function is to set some bits of a variable. From my tests, it all seems to work however it looks like the result of the operation is not assigned back to the variable.
uint16_t setBits(uint16_t target, unsigned int source, int offset, int bitCount) {
unsigned int mask = ~0;
mask = mask >> ((sizeof(mask) * 8) - bitCount);
int rightShift = (sizeof(mask) * 8 - bitCount - offset);
mask = mask << rightShift;
source = source << rightShift;
printHex(target);
printHex((target & ~mask) | (source & mask));
target = (target & ~mask) | (source & mask);
printHex(target);
return target;
}
uint16_t group;
group = 0xabcd;
unsigned int source = 0x12;
group = setBits(group, source, 4, 8);
This would print:
0x0000abcd
0x0120abcd
0x0000abcd
Which for me means that (target & ~mask) | (source & mask) gives the correct result (0x0120abcd), however this result is not assigned back to target (which is still set to 0x0000abcd). Any idea what I’m doing wrong?
Look at the type for
target:It’s only 16 bits, but you try to mask in bits higher than that.