1

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?

7
  • I think your question is answered by this Q&A. Please let us know whether this indeed answers your question, then we can mark it as duplicate. Commented Jan 4, 2019 at 16:51
  • 1
    Possible duplicate of Show u8 slice in hex representation Commented Jan 4, 2019 at 17:08
  • 1
    How is the "binary" part of the question answered by this other QA ? Commented Jan 4, 2019 at 17:11
  • That's awesome it works for hex! Unfortunately that doesn't work for binary output, which is where I'm at right now Commented Jan 4, 2019 at 17:49
  • I updated the question to get rid of hex references, so it's clearer it cares about binary (I originally didn't realise you could do any, so I was trying to be more general. My mistake!) Commented Jan 4, 2019 at 17:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The intermediate String is not needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.