Search code examples
javabit-manipulation

how does below bit manipulation code works?


import java.io.*;

class GFG {
  public static void main (String[] args) {
    int s=4;
    int k=3;
    int a=s^k;
    int b=a & -a;
    System.out.println(b);
  } 
}

I have compiled the above code it gives 1 as the output. But I can't get that how it is compiling. if I do XOR OPERATION between s and k it will give 111(7). but don't know how b=a & -a working please explain.*


Solution

  • Think of it in binary.

    s = 100
    k = 011
    

    enter image description here

    a = s^k = 100 ^ 011 = 111
    

    To get negative number invert all digits and add 1

        -a = invert a + 1 = 000 + 001 = 001
        
         a & -a = 111 & 001 = 001 = decimal 1