Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 803
Lukas Kalbertodt Avatar asked Jul 28 '18 11:07

Lukas Kalbertodt


People also ask

What is the use of << shift operator?

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.

How many types of shift operators are there?

Shift operators are classified into two types based on the shifting position of the bits.

Which are the logical shift operations?

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.


1 Answers

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.

like image 71
Shepmaster Avatar answered Oct 07 '22 00:10

Shepmaster