Maybe they wanted you to show how to write a common set / reset fragment without branches ...
This can be done using
value = (value & ~(1 << bit)) | (bitval << bit);
where bit is the position of the bit, and bitval is 1 for set and 0 for reset.
Something a little more general:
value = (value & ~(k1 << bit)) ^ (k2 << bit);
which implements several operations:
k1=0 and k2=0 does nothingk1=0 and k2=1 toggles the bitk1=1 and k2=0 clears the bitk1=1 and k2=1 sets the bit
More generally with
value = (value & a) ^ x;
you can change several value bits to
aj=0 , xj=0 β setting them to 0aj=0 , xj=1 β setting them to 1aj=1 , xj=0 β leave them untouchedaj=1 , xj=1 β flip them
depending on the previously calculated constants a and x ( aj and xj is the value of the jth bit in constants).
for instance
value = (value & 0x0F) ^ 0x3C;
with one operation will be
- leave untouched bit 0 and 1 - flip bits 2 and 3 - set to 1 bits 4 and 5 - set to 0 all other bits
source share