Skip to content

Instantly share code, notes, and snippets.

@hilda8519
Created August 2, 2014 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hilda8519/c32362e64c608da321ab to your computer and use it in GitHub Desktop.
Save hilda8519/c32362e64c608da321ab to your computer and use it in GitHub Desktop.
public class BitManipulaation {
public static int rewrite(int n, int m,int i, int j){
//to all ones: 11111111111111111111111111111111
int allOne = ~0;
//all ones before j, then 0s
int left = allOne << (j + 1);
//all 0s before i, then 1s
int right = ((1 << i) - 1);
//all ones, but range i - j are 0s
int mask = left | right;
//clear bits through j to i
int clear = n & mask;
//move M to the right place
int shift = m << i;
//clear | shift
return clear | shift;
}
public static void main(String[] args) {
int N = 0b10000000000;
int M = 0b10011;
int i = 2;
int j = 6;
System.out.println(Integer.toBinaryString(rewrite(N, M, i, j)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment