Reputation: 307
I am reading TCPPPL by Stroustrup. It gives an example of a function that extracts the middle 16 bits of a 32 bit long like this:
unsigned short middle(long a){ return (a>>8)&0xffff;}.
My question is: isn't it extracting the last 16 bits? Tell me how am I wrong.
Upvotes: 3
Views: 809
Reputation: 171167
a >> 8
will right-shift the value in a
by 8 bits. The low 8 bits are forgotten, and bits previously numbered 31–8 now get moved (renumbered) to 23–0. Finally, masking out the higher 16 bits leaves you with bits 15–0, which were originally (before the shift) at positions 23–8. Voila.
Upvotes: 3
Reputation: 77
a is going to right shift 8-bit (a>>8
) before bitwise and operation.
Upvotes: 1
Reputation: 40120
It does indeed extract the middle 16 bits:
// a := 0b xxxx xxxx 1111 1111 1111 1111 xxxx xxxx
a>>8; // 0b 0000 0000 xxxx xxxx 1111 1111 1111 1111
&0xffff // 0b 0000 0000 0000 0000 1111 1111 1111 1111
Upvotes: 7
Reputation: 11940
Have you noticed the >>8
part? It shifts the argument right by eight bits, first.
Upvotes: 0