Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 25, 2014 03:59
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 chrislukkk/b634340fb10b2ddb13c5 to your computer and use it in GitHub Desktop.
Save chrislukkk/b634340fb10b2ddb13c5 to your computer and use it in GitHub Desktop.
Career cup 5.1
package Chapter5;
public class BitManipulation {
public static int overwrite(int n, int m, int i, int j) {
int b = j - i + 1;
// create mask with 0s from i to j and 1s in other positions
int mask = 1;
while (b > 0) {
mask *= 2;
b--;
}
mask = ~((mask - 1) << i);
// mask & n set i-j bits in N be 0
// | (m << i) set i-j bits in N be the ones in M
return mask & n | (m << i);
}
//print binary presentation of a positive integer
private static void binaryRepr(int n) {
String s = "";
while (n > 0) {
s += (n % 2);
n /= 2;
}
for (int i = s.length() - 1; i >= 0; i--)
System.out.print(s.charAt(i));
System.out.println();
}
public static void main(String[] args) {
binaryRepr(1024);
binaryRepr(35);
int res = overwrite(1024, 19, 2, 6);
binaryRepr(res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment