marinama
marinama

Reputation: 21

clear all bits from MSB through i (inclusive)

Below is the code about clearing all the MSB’s (Most Significant Bits) through i (inclusive)

public int clearBitsMSBThrough(int num, int i) {
    int mask = ( 1 << (i + 1) ) - 1;
    return num & mask;
}

I am confused about "inclusive". For example, if the number is 0011 1010 and i = 3. mask will be 0000 1111, and result is 0000 1010,but the bit in position 3 is not cleared as zero.

Am I misunderstanding the question? And I think it should be:

int mask = (1 << i) - 1;

Upvotes: 0

Views: 2037

Answers (1)

Piyush Mattoo
Piyush Mattoo

Reputation: 16143

public int clearBitsMSBThrough(int num, int i) {    
   int mask = (1 << i) - 1;
   return num & mask;
}

Skimming through the binary subtraction might help in this regard.

Upvotes: 3

Related Questions