Created
July 15, 2016 12:29
-
-
Save akshaynagpal/9f1c0fa83f101cec0b0f453927564df0 to your computer and use it in GitHub Desktop.
clear n bits in a binary number from both sides
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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