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?
There's a crate for this: hex-slice.
For example:
Rust 1.26.0 and up
The
:x?
"debug with hexadecimal integers" formatter can be used:It can be combined with the pretty modifier as well:
If you need more control or need to support older versions of Rust, keep reading.
Rust 1.0 and up
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: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 typeByteBuf(&[u8])
to use it:Usage: