Skip to content

Instantly share code, notes, and snippets.

@marcouberti
Created October 2, 2018 11:33
Show Gist options
  • Save marcouberti/d84a54a72a41d714e14afda307450d9b to your computer and use it in GitHub Desktop.
Save marcouberti/d84a54a72a41d714e14afda307450d9b to your computer and use it in GitHub Desktop.
binary operators and bit masks in Java
public class BinaryOperationsAndBitmasks {
public static void main(String[] args) {
new BinaryOperationsAndBitmasks().bitsOperations();
}
/**
* Basic bitmap operations
*/
private void bitsOperations() {
int a = 0b101;
int b = 0b111;
System.out.println("a: " + a);
System.out.println("~a: " + ~a);
System.out.println("a & ~a: " + (a & ~a));
System.out.println("~a + 1: " + (~a + 1));//two's complement N -> -N
System.out.println("b: " + b);
System.out.println("~b: " + ~b);
System.out.println("b & ~b: " + (b & ~b));
System.out.println("~b + 1: " + (~b + 1));//two's complement N -> -N
System.out.println("a & b: " + (a & b));
System.out.println("a | b: " + (a | b));
System.out.println("a ^ b: " + (a ^ b));// XOR 1 if different
}
/**
* Get the number of bit used by a generic int
* @return
*/
private int getIntegerBitCount() {
int a = Integer.MAX_VALUE;
int bit_count = 1;
while(((a >>> 1) & 1) == 1) {
a = a >>> 1;
bit_count++;
}
System.out.println(bit_count+1);
return bit_count+1;//+1 for sign bit
}
/**
* Bit mask usage
*/
private void bitMask() {
// indices: 0, 1, 2 , ..., N
// mapping between indices and mask value
// 0 -> 2^0
// 1 -> 2^1
// ....
// N -> 2^N
// masks
short AMMO = 1;
short LIFE = 2;
short FOOD = 4;
short WATER = 8;
short FANTASY = 16;
short PANDORA = 32;
short TRAVEL = 64;
// let's create a 32 bit bit mask
int bitMask = 0; // set all bit to 0
// if we want to raise the flag at position 1
bitMask = bitMask | LIFE;
// if we want to raise the flag at position 3
bitMask = bitMask | WATER;
// if we want to raise the flag at position 4
bitMask = bitMask | FANTASY;
// if we want to raise multiple flags
bitMask = bitMask | AMMO | PANDORA | TRAVEL | FOOD; // we set to 1 indices 0, 5, 6
System.out.println("Bitmask before unset:" + bitMask);
// if we want to unflag indices
bitMask &= ~(AMMO | LIFE | WATER | FANTASY | PANDORA | TRAVEL | FOOD);
System.out.println("Bitmask after unset:" + bitMask);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment