首页 > 解决方案 > 当值在向量中时,我可以将调试输出格式化为二进制吗?

问题描述

在 Rust 中,您可以格式化不同基数的数字,这对于位旋转非常有用:

println!("{:?} {:b} {:x}", 42, 42, 42); // 42 101010 2a

理想情况下,这也适用于向量!虽然它适用于十六进制:

println!("{:#x?}", vec![42, 43, 44]); // [ 0x2a, 0x2b, 0x2c ]

它不适用于二进制:

println!("{:b}", vec![42, 43, 44]); // I wish this were [101010, 101011, 101100]

而是给予:

特征界限std::vec::Vec<{integer}>: std::fmt::Binary不满足

有没有办法在向量中进行二进制格式化?

标签: rust

解决方案


嗯,直接的方式,不,但我会做这样的事情:

use std::fmt;

struct V(Vec<u32>);

// custom output
impl fmt::Binary for V {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // extract the value using tuple idexing
        // and create reference to 'vec'
        let vec = &self.0;

        // @count -> the index of the value,
        // @n     -> the value
        for (count, n) in vec.iter().enumerate() { 
            if count != 0 { write!(f, " ")?; }

            write!(f, "{:b}", n)?;
        }

        Ok(())
    }
}

fn main() {
    println!("v = {:b} ", V( vec![42, 43, 44] ));
}

输出:

$ rustc v.rs && ./v
v = 101010 101011 101100

我在用着rustc 1.31.1 (b6c32da9b 2018-12-18)

Rust fmt::binary引用。

Rust fmt::显示参考。


推荐阅读