I tried to find exact information about how the <<
and >>
operators work on integers, but I couldn't find a clear answer (the documentation is not that great in that regard).
There are two parts of the semantics that are not clear to me. First, what bits are "shifted in"?
0b1110_1010u8 << 4 == 0b1010_0000u8
), or 0b1110_1010u8 << 4 == 0b1010_1110u8
), orAdditionally, how does shifts work with signed integers? Is the sign bit also involved in the shift or not? Or is this unspecified?
The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
Shift operators are classified into two types based on the shifting position of the bits.
In computer science, a logical shift is a bitwise operation that shifts all the bits of its operand. The two base variants are the logical left shift and the logical right shift. This is further modulated by the number of bit positions a given value shall be shifted, such as shift left by 1 or shift right by n.
What are the exact semantics of Rust's shift operators?
There are none. The shift operators are a user-implementable trait and you can do basically anything you want in them. The documentation even shows an example of "[a]n implementation of Shr
that spins a vector rightward by a given amount."
how the
<<
and>>
operators work on integers,
The reference has a section on Arithmetic and Logical Binary Operators. Most usefully, it contains this footnote:
Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
Logical shifting and arithmetic shifting are preexisting computer science terms with established definitions.
Zeroes are shifted in
Yes.
the bits rotate
No. There are separate methods for rotating left and right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With