0

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?

SCdF
  • 57,260
  • 24
  • 77
  • 113
  • I think your question is answered by [this Q&A](https://stackoverflow.com/questions/27650312/show-u8-slice-in-hex-representation). Please let us know whether this indeed answers your question, then we can mark it as duplicate. – Lukas Kalbertodt Jan 04 '19 at 16:51
  • 1
    Possible duplicate of [Show u8 slice in hex representation](https://stackoverflow.com/questions/27650312/show-u8-slice-in-hex-representation) – Tristo Jan 04 '19 at 17:08
  • How is the "binary" part of the question answered by this other QA ? – Denys Séguret Jan 04 '19 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 – SCdF Jan 04 '19 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!) – SCdF Jan 04 '19 at 17:53
  • OP, is there a problem with the answer ? Why didn't you accept it? – Denys Séguret Jan 09 '19 at 10:36
  • @DenysSéguret I was waiting to see if there was an answer that wasn't writing custom code to do it, which is IMO the defacto non-answer to any of these library-style questions. It's been sitting around for awhile though, so it's the best answer, at least for now. – SCdF Jan 09 '19 at 14:15

1 Answers1

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.

Muzol
  • 301
  • 1
  • 11
  • 1
    The intermediate `String` is [not needed](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a4e46f4b81325d268629a112075ebda8). – Anders Kaseorg Jan 05 '19 at 01:40