Captain Obvious
Captain Obvious

Reputation: 785

What happens when using this sequence of bitwise operators

i came across this function in javascript

function(x) {
    return (x >> 8 << 8) ^ x;
};

it is used to convert an x to a byte representation. I understand what the bitwise operations do, however i don't understand what happens, as (122 >> 8 << 8) prints out 0.

Upvotes: 1

Views: 50

Answers (1)

rishicomplex
rishicomplex

Reputation: 36

x >> 8

This right shifts x 8 times, effectively clearing the least significant 8 bits.

(x >> 8) << 8

This left shifts the above quantity by 8 bits. Thus, we get x, with the least significant 8 bits set to 0. If x (16 bit number) was initially 0b0001000101010101, it first becomes 0b0000000000010001, and finally becomes 0b0001000100000000.

(x >> 8 << 8) ^ x

This will xor the above number with x, leaving the least significant 8 bits intact and clearing all the rest to 0. Thus, the least significant byte is obtained. It will work in your case as well, since 122 is less than 2^8. Xoring 122 with 0 returns the least significant byte - 122 itself.

Upvotes: 2

Related Questions