Logical and Arithmetic Right Shifts
A logical shift inserts zeros at the high end of a fixed-width field. An arithmetic shift extends its sign bit in a two's-complement interpretation.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Sort out one negative pattern
Four-bit 1100 means minus four. A one-place logical shift produces 0110. Sign-extending the same original arithmetic shift produces 1110, which represents minus two. See two's-complement reading.
Choose after interpreting the field
Extracting high bits of an unsigned code calls for zero fill. Dividing signed values by two needs the language's rounding rule as well. Floor division explains why minus three divided toward negative infinity gives minus two.[1]
Follow the bits inserted at the left
For eight-bit pattern 11101100, logical right shift by two inserts two zeros. Arithmetic right shift inserts two ones if the model sign-extends. The pattern represents minus twenty in two's complement, whose arithmetic result is minus five in this case. See two's complement reading.
Input 11101100
Logical right 2 00111011 (59 unsigned)
Arithmetic right 2 11111011 (-5 signed)
Test negative odd numbers as well
With arithmetic shift, dividing negative odd values by a power of two rounds toward negative infinity under this bit model. Some integer division operators instead round toward zero. Document the rounding direction your runtime uses for each operation.