Home > Software design >  how does below bit manipulation code works?
how does below bit manipulation code works?

Time:11-08

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.*

CodePudding user response:

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

CodePudding user response:

-x == ~x 1

Negative is ones-complement 1

Should  x     be ababab10..0 (repeated zeros at the end)
then    ~x    is bababa01..1
then   ~x 1   is bababa10..0
then   x&-x   is 0....010..0

So x & -x gives the right most bit 1 of x.

For 7 that would be 1; 12 -> 4, 6 -> 2, 14 -> 2, 8 -> 8, 24 -> 8.

To count the number of bits:

int bitCount(int n) {
    int count = 0;
    while (n != 0) {
        n ^= (n & -n); // Remove the right-most bit.
          count;
    }
    return count;
}
  • Related