如何在 Rust 中操作二进制数?

2024-01-02

我如何在 Rust 中处理和执行数学运算,例如添加或除两个二进制数?

在Python中,有像这样的东西 https://kite.com/python/answers/how-to-add-two-binary-numbers-in-python:

bin(int('101101111', 2) + int('111111', 2))

除非您需要使用浮点数,否则它可以正常工作。


Rust 中的二进制数可以使用前缀定义0b,类似于0o and 0x八进制和十六进制数字的前缀。

要打印它们,您可以使用{:b}格式化程序。

fn main() {
    let x = 0b101101111;
    let y = 0b111111;
    println!("x + y = {:b} that is {} + {} = {} ", x + y, x, y, x + y);

    let a = 0b1000000001;
    let b = 0b111111111;
    println!("a - b = {:b} that is {} - {} = {} ", a - b, a, b, a - b);

    let c = 0b1000000001;
    let d = 0b111111111;
    println!("c * d = {:b} that is {} * {} = {} ", c * d, c, d, c * d);

    let h = 0b10110101101;
    let r = 0b101;
    println!("h / r = {:b} that is {} / {} = {} ", h / r, h, r, h / r);
    println!("h % r = {:b} that is {} % {} = {} ", h % r, h, r, h % r);
}

输出是:

x + y = 110101110 that is 367 + 63 = 430 
a - b = 10 that is 513 - 511 = 2 
c * d = 111111111111111111 that is 513 * 511 = 262143 
h / r = 100100010 that is 1453 / 5 = 290 
h % r = 11 that is 1453 % 5 = 3 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Rust 中操作二进制数? 的相关文章

随机推荐