Pushing &u8 values to a string

Hi all.
I have a loop that iterates through some u8 values.
I want to push each value's HEX equivalent into a string but not sure how.

The code I have is as follows:

fn main() {
    let mut signature_string = String::new();  //this is the variable I'd like to hold the result
    let signature_code = [177,187,102,36,165,137,39,63,52,197,173,13,168,216,95,3,175,113,213,98,52,77,175,152,79,188,119,141,52,19,19,53,]; //in my program this is the array of u8 numbers
    for a in signature_code().iter() { 
     println!(" N: {:x?}", a); //this prints the HEX version of the u8 but how do I get this into my string?
     signature_string.push(a);  //this fails and gives me the error below
    }
    println!("the entire array HEX as a single string: {}", signature_string);
}

The error I get is the following:

   |
31 |      signature_string.push(a);
   |                            ^ expected char, found &u8
   |
   = note: expected type `char`
              found type `&u8`

How can I convert each U8 value to it's HEX equivalent and push that value to a single string?

playground link

Thanks all!

You can use the std::fmt::Write trait and the write! macro to append formatted values to a String:

fn main() {
    use std::fmt::Write; // needed by the `write!` macro

    let mut signature_string = String::new();
    let signature_code = [177,187,102,36,165,137,39,63,52,197,173,13,168,216,95,3,175,113,213,98,52,77,175,152,79,188,119,141,52,19,19,53,]; //in my program this is the array of u8 numbers
    for a in signature_code.iter() { 
        write!(signature_string, "{:02x}", a);
    }
    println!("the entire array HEX as a single string: {}", signature_string);
}
2 Likes

Brilliant this solved it. Thanks so much @mbrubeck!