I tried to find exact information about how the
>> 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"?
- Zeroes are shifted in from one side (i.e.
0b1110_1010u8 << 4 == 0b1010_0000u8), or
- the bits rotate (i.e.
0b1110_1010u8 << 4 == 0b1010_1110u8), or
- it's unspecified (like overflowing behavior of integers is unspecified), or
- something else.
Additionally, 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."
>>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.
Zeroes are shifted in
the bits rotate