Show u8 slice in hex representation

后端 未结 3 461
清酒与你
清酒与你 2020-11-28 14:26

I need to convert &[u8] to a hex representation. For example [ A9, 45, FF, 00 ... ].

The trait std::fmt::UpperHex is not i

3条回答
  •  春和景丽
    2020-11-28 14:59

    Since the accepted answer doesn't work on Rust 1.0 stable, here's my attempt. Should be allocationless and thus reasonably fast. This is basically a formatter for [u8], but because of the coherence rules, we must wrap [u8] to a self-defined type ByteBuf(&[u8]) to use it:

    struct ByteBuf<'a>(&'a [u8]);
    
    impl<'a> std::fmt::LowerHex for ByteBuf<'a> {
        fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
            for byte in self.0 {
                try!( fmtr.write_fmt(format_args!("{:02x}", byte)));
            }
            Ok(())
        }
    }
    

    Usage:

    let buff = [0_u8; 24];
    println!("{:x}", ByteBuf(&buff));
    

提交回复
热议问题