What are the exact semantics of Rust's shift operators?

  • A+
Category:Languages

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

  • 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."


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: