How do I print a vector of u8 as a string?

前端 未结 4 1158
误落风尘
误落风尘 2021-02-19 01:45

Here\'s my code:

let mut altbuf: Vec = Vec::new();

// Stuff here...

match stream.read_byte() {
    Ok(d) => altbuf.push(d),
    Err(e) => { pri         


        
4条回答
  •  死守一世寂寞
    2021-02-19 01:55

    If your altbuf is a vector of u8 as shown, this should work:

    println!("{:?}", altbuf);
    

    Here is an edited piece of code I have that does something similar:

    let rebuilt: Vec;
    
    unsafe {
        ret = proc_pidpath(pid, buffer_ptr, buffer_size);
        rebuilt = Vec::from_raw_parts(buffer_ptr as *mut u8, ret as usize, buffer_size as usize);
    };
    
    println!("Returned a {} byte string", ret);
    println!("{:?}", rebuilt);
    

    That rebuilds a vector of u8 values from a buffer filled by a C function called via FFI so the bytes could be anything, maybe not valid UTF-8.

    When I run it, the output is:

    Returned a 49 byte string

    [47, 85, 115, 101, 114, 115, 47, 97, 110, 100, 114, 101, 119, 47, 46, 114, 98, 101, 110, 118, 47, 118, 101, 114, 115, 105, 111, 110, 115, 47, 49, 46, 57, 46, 51, 45, 112, 51, 57, 50, 47, 98, 105, 110, 47, 114, 117, 98, 121]

    You could format the numbers printed (in hex, octal, etc) using different format strings inside the {}.

    You can get a String from that using String::from_utf8(rebuilt) - which may return an error.

    match String::from_utf8(rebuilt) {
        Ok(path) => Ok(path),
        Err(e) => Err(format!("Invalid UTF-8 sequence: {}", e)),
    }
    

提交回复
热议问题