rust - 将 Bitv 转换为 uint

标签 rust

我正在尝试将 Bitv 转换为 uint。

use std::collections::Bitv;
use std::num::Float;

fn main() {
    let mut bv = Bitv::with_capacity(3,false);
    bv.set(2,true); // Set bit 3
    let deci = Vec::from_fn(bv.len(),|i| if bv.get(i) { 
                                    (i as f32).exp2() 
                                    } else { 0f32 }).iter()
                                                    .fold(0u, |acc, &n| acc+n as uint);
    println!["{}",deci] // 4
}   

行得通。虽然我想知道是否有任何我不知道的库函数,或者是否有其他更好的方法。

最佳答案

我对您的代码进行了一些转换。

不要使用 float

使用rust 1.0

let vec: Vec<_> = (0..bv.len()).map(|i| {
    if bv[i] {
        1 << i
    } else {
        0
    }}).collect();
let deci = vec.iter().fold(0, |acc, &n| acc + n);

原创

let vec = Vec::from_fn(bv.len(), |i| {
    if bv.get(i) {
        1u << i
    } else {
        0u
    }});
let deci = vec.iter().fold(0u, |acc, &n| acc + n);

不用数组,只用元组

使用rust 1.0

let deci = bv.iter()
    .fold((0, 0), |(mut acc, nth), bit| {
        if bit { acc += 1 << nth };
        (acc, nth + 1)
    }).0;

原创

let deci = bv.iter()
    .fold((0u, 0u), |(mut acc, nth), bit| {
        if bit { acc += 1 << nth };
        (acc, nth + 1)
    }).0;

迭代器的更多用法

使用rust 1.0

let deci = bv.iter()
    .enumerate()
    .filter_map(|(nth, bit)| if bit { Some(1 << nth) } else { None })
    .fold(0, |acc, val| acc + val);

原创

let deci = bv.iter()
    .enumerate()
    .filter_map(|(nth, bit)| if bit { Some(1 << nth) } else { None })
    .fold(0u, |acc, val| acc + val);

理想情况下,您可以重新组织代码以利用 to_bytes ,但位的顺序与您的示例不同。

关于rust - 将 Bitv 转换为 uint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27590552/

相关文章:

file - 使用 BufReader 逐行读取文件,存储到数组中

rust - 如何在二进制项目中使用 src 文件夹外部的模块,例如用于集成测试或基准测试?

vector - 不重新借用可变切片时在 for 循环中移动错误

math - 编译器是否优化数学表达式?

rust - `token` 在 rust 中传递到 HeaderValue 时存活时间不够长

rust - 几个共享状态的托管闭包?

rust - Rust 中的文件系统监视

rust - 受本地定义的公共(public)特征约束的核心特征的全面实现

arrays - 如何在 Rust 的结构中实现动态二维数组?

rust - 在 Gentoo 上的 IntelliJ IDEA 中,由于 gentoo 不使用 rustup,我该如何附加 rust stdlib 源?