Binary representation of array of bytes?

I am trying to assemble an array of bytes from variables and I want to print out the representation for debugging before I attempt to use it. The problem is [u8] and &[u8] and [u8;96] all do not implement the Binary trait so if the variable is any of those, I'm stuck.

What are my options to build a serialized binary object from a [u8;96] or [u8]. Surely this is a solved problem, but I can't seem to find any straight forward solutions in all my searching.

//all of the prints fail
let x = [0u8;96];
let y = [0u8;96];
let z = [0u8;96];
println!("{:b}",x);
println!("{:b}",y[..]);
println!("{:b}",&z[..]);

Even if I try to implement Binary for the a type I get an error:

impl fmt::Binary for Serialized{
    fn fmt(&self, f: &mut fmt::Formatter<'_>)->fmt::Result{
        let val = self.serial;
        fmt::Binary::fmt(&val,f)
    }
}

I get the error:
the trait bound [u8; 96]: Binary is not satisfied
the trait Binary is not implemented for [u8; 96] rustc(E0277)

You may want to use newtype to to implement Binary for :

struct Bytes<'a>(&'a [u8]);

impl<'a> std::fmt::Binary for Bytes<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "[")?;
        for byte in self.0 {
            std::fmt::Binary::fmt(byte, f)?;
            writeln!(f, ",")?;
        }
        writeln!(f, "]")?;
        Ok(())
    }
}

let a = [48; 32];
println!("{:#b}", Bytes(&a));
1 Like

This wouldn't solve your problem short-term, but consider making a PR to the standard library to add that. It seems like it'd be useful functionality to have Binary and UpperHex and friends for byte arrays and slices.

(Though that's alot of impls, so you might want to get a "seems reasonable" from libs first before spending time writing it.)

3 Likes

I don't think a lot of impls are required, just a wrapper that converts Debug to Binary: like this.

2 Likes

The only reason I can immediately think of that it hasn't already been done is endian-ness. BE and LE would need a different representation right? Not sure how much that complicates things.

Not for u8s, at least.

(UpperHex for u64 and such could have more questions, but for just bytes it shouldn't be controversial.)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.