Rust 1.26.0 and up

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

let data = b"hello";
// lower case
println!("{:x?}", data);
// upper case
println!("{:X?}", data);

let data = [0x0, 0x1, 0xe, 0xf, 0xff];
// print the leading zero
println!("{:02X?}", data);
// It can be combined with the pretty modifier as well
println!("{:#04X?}", data);

Output:

[68, 65, 6c, 6c, 6f]
[68, 65, 6C, 6C, 6F]
[00, 01, 0E, 0F, FF]
[
    0x00,
    0x01,
    0x0E,
    0x0F,
    0xFF,
]

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 wrapper 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 choose to implement multiple traits, like Lower and UpperHex
impl fmt::Display for HexSlice<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            // Decide if you want to pad the value or have spaces inbetween, etc.
            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>
}

You can be even fancier and create an extension trait:

trait HexDisplayExt {
    fn hex_display(&self) -> HexSlice<'_>;
}

impl<T> HexDisplayExt for T
where
    T: ?Sized + AsRef<[u8]>,
{
    fn hex_display(&self) -> HexSlice<'_> {
        HexSlice::new(self)
    }
}

fn main() {
    println!("{}", "world".hex_display());
}
Answer from Shepmaster on Stack Overflow
🌐
Programming Idioms
programming-idioms.org › idiom › 175 › bytes-to-hex-string › 2635 › rust
Bytes to hex string, in Rust
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit). ... fn byte_to_hex(byte: u8) -> (u8, u8) { static HEX_LUT: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f']; let upper = HEX_LUT[(byte ...
Top answer
1 of 6
195

Rust 1.26.0 and up

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

let data = b"hello";
// lower case
println!("{:x?}", data);
// upper case
println!("{:X?}", data);

let data = [0x0, 0x1, 0xe, 0xf, 0xff];
// print the leading zero
println!("{:02X?}", data);
// It can be combined with the pretty modifier as well
println!("{:#04X?}", data);

Output:

[68, 65, 6c, 6c, 6f]
[68, 65, 6C, 6C, 6F]
[00, 01, 0E, 0F, FF]
[
    0x00,
    0x01,
    0x0E,
    0x0F,
    0xFF,
]

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 wrapper 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 choose to implement multiple traits, like Lower and UpperHex
impl fmt::Display for HexSlice<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            // Decide if you want to pad the value or have spaces inbetween, etc.
            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>
}

You can be even fancier and create an extension trait:

trait HexDisplayExt {
    fn hex_display(&self) -> HexSlice<'_>;
}

impl<T> HexDisplayExt for T
where
    T: ?Sized + AsRef<[u8]>,
{
    fn hex_display(&self) -> HexSlice<'_> {
        HexSlice::new(self)
    }
}

fn main() {
    println!("{}", "world".hex_display());
}
2 of 6
29

Use hex::encode from the hex crate.

let a: [u8;4] = [1, 3, 3, 7];
assert_eq!(hex::encode(&a), "01030307");
[dependencies]
hex = "0.4"
🌐
Rust Programming Language
users.rust-lang.org › t › how-to-prints-26-bytes-in-hex-on-a-single-line › 89398
How to prints 26 bytes in hex on a single line? - The Rust Programming Language Forum
February 16, 2023 - Following is a tcp server code reading data from my tcp client serial to ethernet board and storing on a mutable buffer and printing. I wrote this code with the help of this article. (How to Build a Client Server Application using Rust | Engineering Education (EngEd) Program | Section) - credit to the author. let mut buf = [0;26]; for _ in 0..200{ let bytes_read = stream.read(&mut buf)?; println!("Bytes read {}", bytes_read); stream.write(&buf[..bytes_read])?; **println!("f...
🌐
Blogger
illegalargumentexception.blogspot.com › 2015 › 05 › rust-byte-array-to-hex-string.html
Rust: byte array to hex String
This code allows you to express arbitrary octet sequences as hex. pub fn to_hex_string(bytes: Vec
🌐
Rust
docs.rs › hex
hex - Rust
Encodes data as hex string using lowercase characters. ... Encodes some bytes into a mutable slice of bytes.
🌐
crates.io
crates.io › crates › hexhex
hexhex - crates.io: Rust Package Registry
Display bytes as hex with no (heap) allocations · Convert bytes to hex String · Convert hex &str or &[u8] to a new byte vector · Convert hex &str or &[u8] to bytes in a preallocated buffer · Macro for all your compile-time hex to bytes conversion needs ·
🌐
GitHub
github.com › debris › rustc-hex › blob › master › src › lib.rs
rustc-hex/src/lib.rs at master · debris/rustc-hex
/// use rustc_hex::ToHex; /// /// fn main () { /// let str: String = [52,32].to_hex(); /// println!("{}", str); /// } /// ``` fn to_hex<T: FromIterator<char>>(&self) -> T { ToHexIter::new(self.iter()).collect() } } · impl<'a, T: ?Sized + ToHex> ToHex for &'a T { fn to_hex<U: FromIterator<char>>(&self) -> U { (**self).to_hex() } } · /// An iterator converting byte slice to a set of hex characters.
Author: debris
🌐
GitHub
github.com › thenewwazoo › simple-hex
GitHub - thenewwazoo/simple-hex: Simple Rust byte-to-hex and hex-to-byte library
This is a (very!) simple library that turns nibbles into hex characters and vice versa. I wrote this to avoid pulling in core::fmt (and because it was faster than finding an alternative).
Author: thenewwazoo
🌐
Brandeis University
cs.brandeis.edu › ~cs146a › rust › doc-02-21-2015 › src › serialize › hex.rs.html
hex.rs.html -- source
// // ignore-lexer-test FIXME #15679 ... pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> String; } static CHARS: &'static[u8] = b"0123456789abcdef"; impl ToHex for [u8] { /// Turn a vector of `u8` bytes ...
Find elsewhere
🌐
Lib.rs
lib.rs › crates › const-hex
const-hex — Rust formatting library // Lib.rs
May 23, 2026 - This crate provides a fast conversion of byte arrays to hexadecimal strings, both at compile time, and at run time.
🌐
docs.rs
docs.rs › hex › latest › hex › fn.encode.html
encode in hex - Rust
Encodes `data` as hex string using lowercase characters.
🌐
crates.io
crates.io › crates › array-bytes
array-bytes - crates.io: Rust Package Registry
June 4, 2025 - // Hexify. array_bytes::Hexify::hexify time: [10.978 µs 10.997 µs 11.021 µs] const_hex::encode time: [941.68 ns 946.55 ns 951.44 ns] faster_hex::hex_string time: [11.478 µs 11.498 µs 11.519 µs] faster_hex::hex_encode_fallback time: [11.546 µs 11.563 µs 11.580 µs] hex::encode time: [85.347 µs 85.524 µs 85.751 µs] rustc_hex::to_hex time: [46.267 µs 47.009 µs 47.759 µs] // Dehexify.
🌐
Rust
docs.rs › hexhex
hexhex - Rust
use hexhex::{Hex, Case}; let bytes = [0xc0, 0xff, 0xee]; println!("{}", Hex::new(&bytes).with_prefix(true).with_case(Case::Upper)); // no allocations, prints "0xC0FFEE" Hex implements the core::fmt::Display trait, so conversion to string is as easy as:
🌐
Rust
dtantsur.github.io › rust-openstack › rustc_serialize › hex › trait.FromHex.html
rustc_serialize::hex::FromHex - Rust
Convert any hexadecimal encoded string (literal, @, &, or ~) to the byte values it encodes. You can use the String::from_utf8 function to turn a Vec<u8> into a string with characters corresponding to those values. This converts a string literal to hexadecimal and back. extern crate rustc_serialize; ...
🌐
MojoAuth
mojoauth.com › binary-encoding-decoding › base16-hexadecimal-with-rust
Base16 (Hexadecimal) with Rust | Binary Encoding Techniques Across Programming Languages
This library provides straightforward functions for converting binary data into its hexadecimal string representation. Using the hex::encode function is simple. You pass a slice of bytes (&[u8]) or a vector of bytes (Vec<u8>) to it, and it returns ...
🌐
Rust Programming Language
users.rust-lang.org › t › printing-hex-octa-byte-in-rust › 40877
Printing hex / octa / byte in rust - The Rust Programming Language Forum
April 13, 2020 - while printing hex / octa / byte ,it print is decimal form . is it possible to print hex / octa / byte numbers as it is which is declare to a variable using let without using string or character datatype ?
🌐
Rust Programming Language
users.rust-lang.org › help
How to easily translate hex string into usize or bytes - help - The Rust Programming Language Forum
January 3, 2024 - for example, I'm gotting "0x2A2F" and how to translate it into the actual number? I want a high performance way without other crates. Or if there is a good crate implemented for it, I'm going to learn about it.