Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask for clearing m bits after n LSBits

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?

like image 665
Skanda Avatar asked Mar 17 '23 07:03

Skanda


1 Answers

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)
like image 143
luser droog Avatar answered Mar 30 '23 21:03

luser droog