Rust 的移位运算符的确切语义是什么?
What are the exact semantics of Rust's shift operators?
我试图找到有关 <<
和 >>
运算符如何处理整数的确切信息,但我找不到明确的答案(the documentation 在那个方面)。
有两部分语义我不清楚。首先,"shifted in"是什么位?
- 零从一侧移入(即
0b1110_1010u8 << 4 == 0b1010_0000u8
),或
- 位循环(即
0b1110_1010u8 << 4 == 0b1010_1110u8
),或
- 它是未指定的(比如整数的溢出行为是未指定的),或者
- 其他。
此外,shift 如何处理有符号整数?符号位是否也参与移位?或者这是未指定的?
关于特征 Shl
和 Shr
的精简文档是有意为之的,以便它们可以采用最适合手头类型的行为(想想新类型!)。
话虽如此,当谈到基本整数类型时,Rust reference 涵盖了它们的行为方式,并带有一些推论:
<<
| Left Shift | std::ops::Shl
>>
| Right Shift* | std::ops::Shr
* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
它还包括一些示例,进一步阐明了这些是常规的 logical/arithmetic 移位:零被插入左移位的最低有效位,最高有效位被扩展为有符号整数在右位移位上。它也是 not a rotation,如方法 rotate_left
和 rotate_right
中所述。
assert_eq!(13 << 3, 104);
assert_eq!(-10 >> 2, -3);
此外,移动太多位可能会被视为算术溢出,而不是未定义的行为。参见:
What are the exact semantics of Rust's shift operators?
有none个。移位运算符是用户可实现的特性,您基本上可以在其中做任何您想做的事情。该文档甚至显示了“Shr
的 [a]n 实现将向量向右旋转给定数量的示例。”
how the <<
and >>
operators work on integers,
参考文献中有一节关于 Arithmetic and Logical Binary Operators。最有用的是,它包含这个脚注:
Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
Logical shifting and arithmetic shifting 是具有既定定义的先前存在的计算机科学术语。
Zeroes are shifted in
是的。
the bits rotate
有不同的方法
我试图找到有关 <<
和 >>
运算符如何处理整数的确切信息,但我找不到明确的答案(the documentation 在那个方面)。
有两部分语义我不清楚。首先,"shifted in"是什么位?
- 零从一侧移入(即
0b1110_1010u8 << 4 == 0b1010_0000u8
),或 - 位循环(即
0b1110_1010u8 << 4 == 0b1010_1110u8
),或 - 它是未指定的(比如整数的溢出行为是未指定的),或者
- 其他。
此外,shift 如何处理有符号整数?符号位是否也参与移位?或者这是未指定的?
关于特征 Shl
和 Shr
的精简文档是有意为之的,以便它们可以采用最适合手头类型的行为(想想新类型!)。
话虽如此,当谈到基本整数类型时,Rust reference 涵盖了它们的行为方式,并带有一些推论:
<<
| Left Shift |std::ops::Shl
>>
| Right Shift* |std::ops::Shr
* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
它还包括一些示例,进一步阐明了这些是常规的 logical/arithmetic 移位:零被插入左移位的最低有效位,最高有效位被扩展为有符号整数在右位移位上。它也是 not a rotation,如方法 rotate_left
和 rotate_right
中所述。
assert_eq!(13 << 3, 104);
assert_eq!(-10 >> 2, -3);
此外,移动太多位可能会被视为算术溢出,而不是未定义的行为。参见:
What are the exact semantics of Rust's shift operators?
有none个。移位运算符是用户可实现的特性,您基本上可以在其中做任何您想做的事情。该文档甚至显示了“Shr
的 [a]n 实现将向量向右旋转给定数量的示例。”
how the
<<
and>>
operators work on integers,
参考文献中有一节关于 Arithmetic and Logical Binary Operators。最有用的是,它包含这个脚注:
Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
Logical shifting and arithmetic shifting 是具有既定定义的先前存在的计算机科学术语。
Zeroes are shifted in
是的。
有不同的方法the bits rotate