fork download
  1. class BitwiseOpsDemo {
  2. public static void main(String[] args) {
  3. java.io.PrintStream out = System.out;
  4.  
  5. int packed = 0;
  6.  
  7. // Enable bits located at 0x20 and 0x2, respectively
  8. packed |= 1 << 5;
  9. packed |= 1 << 2;
  10. out.println("packed = " + Integer.toBinaryString(packed));
  11.  
  12. // To determine what is set at a particular bit, mask the value and compare it with the mask
  13. boolean isShift5 = (packed & 0x20) == 0x20;
  14. boolean isShift6 = (packed & 0x40) == 0x40;
  15.  
  16. // You don’t need to hardcode the mask, you can also compute the mask
  17. int shift2Mask = 1 << 2;
  18. out.println("shift2Mask = " + Integer.toBinaryString(shift2Mask));
  19.  
  20.  
  21. boolean isShift2 = (packed & shift2Mask) == shift2Mask;
  22.  
  23. out.println("fifth = " + isShift5 + " | sixth = " + isShift6 + " | second = " + isShift2);
  24. }
  25. }
Success #stdin #stdout 0.14s 36840KB
stdin
Standard input is empty
stdout
packed = 100100
shift2Mask = 100
fifth = true | sixth = false | second = true