I've been reading the classic Hacker's delight and I am having trouble understanding the difference between logical shift right,arithmetic shift right, and rotate right. Please excuse if the doubt seems too simple.
相关问题
- Index of single bit in long integer (in C) [duplic
- Logical vs. bitwise operator AND
- Delphi XE LiveBindings - Bits to Byte
- Cast some light on population count algorithm
- How do I perform a proper unsigned right shift in
相关文章
- Construction an logical expression which will coun
- Rounded division by power of 2
- How does Java calculate negative numbers?
- Compact a hex number
- One function with different arguments to push cert
- Unpacking a bitfield (Inverse of movmskb)
- Fastest way to count consecutive 1 bits. C++
- Create method which checks if x + y will overflow
First remember that machine words are of fixed size. Say 4, and that your input is:
Then pushing everything one position to the left gives:
Question what to put as X?
a
Now push everything one position to the right gives:
Question what to put as X?
a
d
Roughly.
Logical shift correspond to (left-shift) multiplication by 2, (right-shift) integer division by 2.
Arithmetic shift is something related to 2's-complement representation of signed numbers. In this representation, the sign is the leftmost bit, then arithmetic shift preserves the sign (this is called sign extension).
Rotate has no ordinary mathematical meaning, and is almost an obsolete operation even in computers.
The difference is pretty much explained in the right-most column.
>>
operator in C.Arithmetic shift treats the number as a signed integer (in 2s complement), and "retains" the topmost bit, shifting in zeros if the topmost bit was 0, and ones if it was one. C's right-shift operator has implementation-defined behavior if the number being shifted is negative.
For example, the binary number
11100101
(-27 in decimal, assuming 2s complement), when right-shifted 3 bits using logical shift, becomes00011100
(decimal 28). This is clearly confusing. Using an arithmetic shift, the sign bit would be kept, and the result would become11111100
(decimal -4, which is about right for -27 / 8).Rotation does neither, since topmost bits are replaced by lowermost bits. C does not have an operator to do rotation.