Mask to clean m bits after n LSBits

I was asked this question in an interview to clear m bits after n bits from a 16-bit integer.

Suppose this number is 10010010010100101. Reset three bits after 5 bits from LSBit.

Before: 10011001 110 11001 After: 10011001 000 11001

My mask solution was (~0 << (m+n))+((1<<n)-1)

Is there any solution better than this?

+4
source share
1 answer

I'm not sure about the “best”, 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 these bits from another value,

x & ~(((1u<<m)-1)<<n)
+7
source

All Articles