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

前端 未结 4 1175
误落风尘
误落风尘 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:50

    Use the write method from std::io:

    use std::{io, io::Write};
    
    fn main() -> io::Result<()> {
       io::stdout().write(b"March\n")?;
       Ok(())
    }
    

    It prints a slice of u8, also known as a bytestring.

    io::stdout

    0 讨论(0)
  • 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<u8>;
    
    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)),
    }
    
    0 讨论(0)
  • 2021-02-19 02:06

    To print bytes as a UTF-8 string, use std::str::from_utf8 when the bytes may be malformed. Use the unsafe std::str::from_utf8_unchecked when the bytes are always valid UTF-8.

    println!("{}", std::str::from_utf8(&altbuf).unwrap());
    
    0 讨论(0)
  • 2021-02-19 02:11

    If you look at the String documentation, there are a few methods you could use. There's String::from_utf8 that takes a Vec<u8>, and there's also String::from_utf8_lossy which takes a &[u8].

    Note that a Vec<T> is more-or-less an owned, resizable wrapper around a [T]. That is, if you have a Vec<u8>, you can turn it into a &[u8], most easily by re-borrowing it (i.e. &*some_vec). You can also call any methods defined on &[T] directly on a Vec<T> (in general, this is true of things that implement the Deref trait).

    0 讨论(0)
提交回复
热议问题