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?
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