rust - 当值在向量中时,我可以将调试输出格式化为二进制吗?
问题描述
在 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
不满足
有没有办法在向量中进行二进制格式化?
解决方案
嗯,直接的方式,不,但我会做这样的事情:
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::显示参考。
推荐阅读
- python - Splinter 如何将文本作为输出,
- regex - 开始和结束标签正则表达式
- android - 如何将枚举列表传递给片段?
- powershell - 如何显示当前的 pshostprocess 和 runspace 信息?
- javascript - 访问 JSON 数组中的键名
- amazon-web-services - AWS AppSync WebUI 非常慢
- javascript - blur() 上的“倒带”输入
- zendesk-api - 发布到 Zendesk Api 接收 403
- ruby-on-rails - 无法在 ruby on rails 中翻译 html 代码
- python - Sympy 在求解 ODE 系统时返回“关键错误”