Show u8 slice in hex representation

2019-01-18 22:08发布

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

The trait std::fmt::UpperHex is not implemented for slices (so I can't use std::fmt::format). Rust has the serialize::hex::ToHex trait, which converts &[u8] to a hex String, but I need a representation with separate bytes.

I can implement trait UpperHex for &[u8] myself, but I'm not sure how canonical this would be. What is the most canonical way to do this?

标签: hex rust slice
3条回答
Lonely孤独者°
2楼-- · 2019-01-18 22:49

There's a crate for this: hex-slice.

For example:

extern crate hex_slice;
use hex_slice::AsHex;

fn main() {
    let foo = vec![0u32, 1, 2 ,3];
    println!("{:02x}", foo.as_hex());
}
查看更多
smile是对你的礼貌
3楼-- · 2019-01-18 22:53

Rust 1.26.0 and up

The :x? "debug with hexadecimal integers" formatter can be used:

let data = b"hello";
println!("{:x?}", data);
println!("{:X?}", data);
[68, 65, 6c, 6c, 6f]
[68, 65, 6C, 6C, 6F]

It can be combined with the pretty modifier as well:

let data = b"hello";
println!("{:#x?}", data);
println!("{:#X?}", data);
[
    0x68,
    0x65,
    0x6c,
    0x6c,
    0x6f
]
[
    0x68,
    0x65,
    0x6C,
    0x6C,
    0x6F
]

If you need more control or need to support older versions of Rust, keep reading.

Rust 1.0 and up

use std::fmt::Write;

fn main() {
    let mut s = String::new();
    for &byte in "Hello".as_bytes() {
        write!(&mut s, "{:X} ", byte).expect("Unable to write");
    }

    println!("{}", s);
}

This can be fancied up by implementing one of the formatting traits (fmt::Debug, fmt::Display, fmt::LowerHex, fmt::UpperHex, etc.) on a struct and having a little constructor:

use std::fmt;

struct HexSlice<'a>(&'a [u8]);

impl<'a> HexSlice<'a> {
    fn new<T>(data: &'a T) -> HexSlice<'a> 
        where T: ?Sized + AsRef<[u8]> + 'a
    {
        HexSlice(data.as_ref())
    }
}

// You can even choose to implement multiple traits, like Lower and UpperHex
impl<'a> fmt::Display for HexSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for byte in self.0 {
            // Decide if you want to pad out the value here
            write!(f, "{:X} ", byte)?;
        }
        Ok(())
    }
}

fn main() {
    // To get a `String`
    let s = format!("{}", HexSlice::new("Hello"));

    // Or print it directly
    println!("{}", HexSlice::new("world"));

    // Works with 
    HexSlice::new("Hello");              // string slices (&str)
    HexSlice::new(b"Hello");             // byte slices (&[u8])
    HexSlice::new(&"World".to_string()); // References to String
    HexSlice::new(&vec![0x00, 0x01]);    // References to Vec<u8>  
}
查看更多
欢心
4楼-- · 2019-01-18 23:12

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));
查看更多
登录 后发表回答