u8 数组转换成 string

问题描述

问题来自于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 协议》,转载必须注明作者和本文链接

令狐一冲

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!