Mettepen
Mettepen

Reputation: 51

I am not really sure what this code does (bit manipulation)

I wrote some code I am unit testing right now and for that I made the code below with the help of the internet.

//shows changed bit
    //0010 0101 XOR 0010 0111 = 0000 0010 
    uint8_t XOR = value ^ result;

    int count;
    //count amount of 1's in XOR
    for (count = 0; XOR; XOR >>= 1)
    {
        count += XOR & 1;
    }

Value is the original value, and result is the value but with ONE bit toggled.

I just want to make sure I understand this correctly but please correct me if I am wrong.

The 2nd statement in the for loop the "XOR;" what I think it does is run the for loop while XOR is not 0. And the XOR >>= 1 is that it sets to its self but with the 1 shifted one place to the right.

And the count does a +1 whenever there is a 1 on the last position ?

That's what I make out of it.

Upvotes: 2

Views: 46

Answers (1)

Déjà vu
Déjà vu

Reputation: 28830

If you do

  r = a xor b

and a has only one bit toggled compared to b, r will have that bit at 1, always, all the other bits at 0.

So count will always give 1.

The for loop adds one to count when the LSb (bit 0, right side) is 1. Then XOR is shifted right, all bits going from left to right, the bit 0 taking the value of bit 1 etc. The MSb (bit 7) takes value 0 (XOR is unsigned, so no problem if the MSb was 1 initially).

Thus, eventually XOR will be 0 and the loop will stop.

Upvotes: 1

Related Questions