In the system example, you have a 16 bit integer which holds three values. One value is the 15th bit, one is bits 14-8, and the last is 7-0. In order to extract those values, the common way to do this is to shift over the appropriate number of bits, then mask off the unneeded bits.
For an example, let's use the field 1100 0001 0000 1111. The first value is a 1, the second is 100 0001, and the third is 0000 1111.
To get the first value, shift to the right 15 bits, then AND that with 1. What's really happening is you are ANDing it with a bunch of leading zeros, and then a final one. So in this case, ANDing a one with a one yields one.
It's more interesting (and it makes the reason for the ANDing more apparent) when getting the second value. You right shift 8 bits, ending up with (with leading zeros) 0000 0000 1100 0001. If you were to then get this value, you would end up with 193. The problem here is that we only want the first 7 bits, but we've got that 8th bit in there. So we zero out the high bits by ANDing it with 0111 1111. This results in 0100 0001, or 65.
In reply to Re^3: Shift Operators And Bitwise Operators
by lostjimmy
in thread Shift Operators And Bitwise Operators
by biohisham
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |