【问题标题】:How to make Unsigned right shift (>>>) in rust? [duplicate]如何使无符号右移(>>>)生锈? [复制]
【发布时间】:2022-01-09 16:33:10
【问题描述】:

【问题讨论】:

    标签: rust webassembly wasm-bindgen


    【解决方案1】:

    对于正数,您只需使用移位运算符>>

    但是,对于负数,我假设您处理的是i32。您链接的文档中的行为将负数的二进制表示向右移动。因此,我们首先需要将负整数重新解释为无符号整数。最安全的做法是使用to_be_bytesfrom_be_bytes

    fn main() {
        let a: u32 = 5;
        let b: u32 = 2;
        let c: i32 = -5;
    
        let c_as_u32: u32 = {
            let bytes = c.to_be_bytes();
            u32::from_be_bytes(bytes)
        };
    
        let x = a >> b;
        let y = c_as_u32 >> b;
        
        println!("x = {}", x); // x = 1
        println!("y = {}", y); // x = 1073741822
    }
    
    

    【讨论】:

    • 最好使用to_ne_bytes,因为这不需要在转换过程中重新排列字节。此外,几乎所有现代 CPU 都是 little-endian,因此它总是不如 le_bytes 最佳。 ne_bytes 总是擅长任何平台。
    • 简单地使用c as u32有什么问题?我的印象是这在 Rust 中具有明确定义的行为。
    • The reference states: “在两个相同大小的整数之间进行转换(例如 i32 -> u32)是无操作的(Rust 使用 2 的补码表示固定整数的负值)”,所以 @987654329 @ 应该可以解决问题。
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多