Skip to content

Instantly share code, notes, and snippets.

@akshaynagpal
Created July 15, 2016 12:29
Show Gist options
  • Save akshaynagpal/9f1c0fa83f101cec0b0f453927564df0 to your computer and use it in GitHub Desktop.
Save akshaynagpal/9f1c0fa83f101cec0b0f453927564df0 to your computer and use it in GitHub Desktop.
clear n bits in a binary number from both sides
public static int clearBitsIthrough0(int num,int i){
System.out.println("clearing bits "+i+" to 0 of number:"+Integer.toBinaryString(num));
int mask = ~(0<<31); // mask with all bits set
mask = mask<<i+1; // mask with bits 0 to i cleared
System.out.println("using mask:"+Integer.toBinaryString(mask));
return num & mask;
}
public static int clearBitsMSBthroughI(int num,int i){
System.out.println("clearing bits MSB to "+i+" of number:"+Integer.toBinaryString(num));
int mask = (~(0<<32-(i+1)))<<i; //mask with only last i bits set
mask = ~mask; //complement to get the required mask
System.out.println("using mask:"+Integer.toBinaryString(mask));
return num & mask;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment