Skip to content

Instantly share code, notes, and snippets.

@asimihsan
Created December 14, 2013 22:31
Show Gist options
  • Save asimihsan/7965815 to your computer and use it in GitHub Desktop.
Save asimihsan/7965815 to your computer and use it in GitHub Desktop.
Coding for Interviews - Bit Manipulation
class CodingForInterviewsBitManipulation {
public static int setBit(int number, int index, boolean set) {
if (set)
return number | (1 << index);
else
return number & (~(1 << index));
}
public static boolean getBit(int number, int index) {
int result = (number & (1 << index)) >> index;
return (result == 1);
}
public static void main(String[] args) {
int input = 0b11100110;
// = 0b11101110
System.out.println(Integer.toString(setBit(input, 3, true), 2));
// = 0b11100100
System.out.println(Integer.toString(setBit(input, 1, false), 2));
// false
System.out.println(getBit(input, 0));
// true
System.out.println(getBit(input, 7));
}
}
11101110
11100100
false
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment