u8 陣列轉換成 string

linghuyichong發表於2019-12-23

問題來自於rust英文論壇的一個問題,連結https://users.rust-lang.org/t/pushing-u8-values-to-a-string/36060, 錯誤程式碼如下:

fn main() {
    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,];

    for a in signature_code().iter() { 
         println!(" N: {:x?}", a); 
         signature_string.push(a);  
    }

    println!("the entire array HEX as a single string: {}", signature_string);
}

思路,使用宏來解決,程式碼如下:

fn main() {
    use std::fmt::Write;

    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,]; 

    //for a in signature_code().iter() { 
    for a in signature_code.iter() { 
        //println!(" N: {:x?}", a); 
        //signature_string.push(a);
        write!(signature_string, "{:02x}", a);
    }

    println!("the entire array HEX as a single string: {}", signature_string);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章