SCdF
SCdF

Reputation: 59428

Can I format debug output as binary when the values are in a vector?

In Rust you can format numbers in different bases, which is really useful for bit twiddling:

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

Ideally this would also work for vectors! While it works for hex:

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

It does not work for binary:

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

Instead giving:

the trait bound std::vec::Vec<{integer}>: std::fmt::Binary is not satisfied

Is there a way of doing binary formatting inside vectors?

Upvotes: 1

Views: 2417

Answers (1)

Muzol
Muzol

Reputation: 301

Well a direct way, no, but I would do something like this:

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] ));
}

Output:

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

I'm using rustc 1.31.1 (b6c32da9b 2018-12-18)

Rust fmt::binary reference.

Rust fmt::Display reference.

Upvotes: 2

Related Questions