代码之家  ›  专栏  ›  技术社区  ›  Lukas Kalbertodt

Rust的移位操作符的确切语义是什么?

  •  13
  • Lukas Kalbertodt  · 技术社区  · 6 年前

    我试图找到关于 << >> 运算符处理整数,但找不到清晰的答案( the documentation 在这方面不是很好)。

    语义有两个部分我不清楚。首先,什么位被“移入”?

    • 零点从一侧移入(即 0b1110_1010u8 << 4 == 0b1010_0000u8 )
    • 钻头旋转(即 0b1110_1010u8 << 4 == 0b1010_1110u8 )
    • 未指定(如未指定整数的溢出行为),或
    • 别的东西。

    此外,移位如何处理有符号整数?符号位是否也与移位有关?还是未指明?

    2 回复  |  直到 6 年前
        2
  •  8
  •   E_net4 Tunn    6 年前

    Shl Shr

    Rust reference

    • << std::ops::Shl

    • >> std::ops::Shr

    not a rotation rotate_left rotate_right

    assert_eq!(13 << 3, 104);
    assert_eq!(-10 >> 2, -3);
    

    Is it expected that a too large bitshift is undefined behavior in Rust?