Numeral Systems
Bit Shifting
128
|
64 | 32 | 16 | 8 | 4 | 2 | 1 |
27 |
26 |
25 |
24 |
23 |
22 |
21 |
20 |
0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 |
0 1 0 1 0 0 0 1 => 1*64 + 1*16 + 1*1 = 81
Arithmetic bit shifting to the right with >>
Makes bits fall of
the right and adds zero padding to the left. This is equivalent to arithmetic division.
01010001 = 1*64 + 1*16 + 1*1 = 81
$y = 0b01010001 >> 1
>> 1 … shifting by one position to the right:
01010001 → 00101000 = 1*32 + 1*8 = 40 (ie int(81/2))
Arithmetic bit shifting to the left with <<
Makes bits fall of
the left and adds zero padding to the right. This is equivalent to arithmetic multiplication by 2 to the number on the right of the
operator.
01010001 = 1*64 + 1*16 + 1*1 = 81
$y = 0b01010001 << 1
<< 1 … shifting by one position to the left, we are multiplying by 2 to 1:
<< 1 … shifting by one position to the left, we are multiplying by 2 to 1:
01010001 → 10100010 = 1*128 + 1*32 + 1*2 = 162 (ie 81 * 2)
NOTE
The number of shift positions needs to result in a value within the allowed range of the original value type:
<< 2:
01010001 (81) → 01000100 = 1*64 + 1*4 =68
No comments:
Post a Comment
Note: only a member of this blog may post a comment.