Search code examples
c++bit-manipulationbitwise-operators

What are these bitwise operators doing?


I always struggled with bitwise operators and their practical usage. I found an example online for something I am doing in C++ and was wondering what is going on there.

    for (int i = 0; i < size / 2; ++i)
    {
        queue->push(temp[i] & 0xff);
        queue->push((temp[i] >> 8) & 0xff);
    }

I know roughly what the "And" and the "Shift" operator is doing, but how does that affect the temp variable and the result. Anyone can help understand that?


Solution

  • The first statement, temp[i] & 0xff, extracts the lower 8 bits because 0xff = 1111 1111.

    The second statement, (temp[i] >> 8) & 0xff , first shifts the bits in temp[i] to the right by 8 times, so the bits from position 8 to position 15 will now occupy bits from position 0 to position 7. And when you do the bitwise & with 0xFF, you get the new bits from position 0 to position 7.

    For example -

    Let's say, temp[i] = 0x01020304 then temp[i] & 0xff = 0x04 and (temp[i] >> 8) & 0xff = 0x03