Created
December 14, 2013 22:31
-
-
Save asimihsan/7965815 to your computer and use it in GitHub Desktop.
Coding for Interviews - Bit Manipulation
This file contains hidden or 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
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)); | |
} | |
} |
This file contains hidden or 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
11101110 | |
11100100 | |
false | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment