I was asked this question in an interview to clear m bits after n bits of a 16 bit integer.
Lets say the number is 10010010010100101. Clear three bits after 5 bits from the LSBit.
Before: 1001100111011001 After : 1001100100011001
My solution for the mask was (~0 << (m+n))+((1<<n)-1)
Is there any solution better than this?
I'm not sure about "better", but I always seem to build masks the same way.
((1u<<m)-1)<<n
For m=3 n=5 this gives
000011100000
Then using this mask to clear those bits from another value,
x & ~(((1u<<m)-1)<<n)
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