#serde #hex #hexadecimal


Hexadecimal encoding/decoding with serde

1 unstable release

Uses old Rust 2015

0.1.0 May 30, 2019

#12 in #hexadecimal

Download history 1623/week @ 2021-09-26 3180/week @ 2021-10-03 2465/week @ 2021-10-10 1577/week @ 2021-10-17 1114/week @ 2021-10-24 1362/week @ 2021-10-31 1219/week @ 2021-11-07 890/week @ 2021-11-14 883/week @ 2021-11-21 919/week @ 2021-11-28 903/week @ 2021-12-05 906/week @ 2021-12-12 1724/week @ 2021-12-19 1354/week @ 2021-12-26 1586/week @ 2022-01-02 1246/week @ 2022-01-09

5,960 downloads per month
Used in 20 crates (6 directly)


991 lines

serde-hex Build Status

Rust crate for easy and versatile serialization/deserialization of hexadecimal values.


The serde-hex crate is built around the SerHex trait, which makes it easy to specify custom hexadecimal serialization/deserialization with serde. Once implemented, the SerHex trait is configured via its generic type parameter (e.g.; SerHex<Compact> for hexadecimal values with no leading zeroes, or SerHex<StrictPfx> for leading zeroes and the 0x prefix). Thanks to Rust's very magical compiler, only the components of the serialization/deserialization functionality that your configuration actually uses get compiled in. The most common way to use SerHex is when deriving the Serialize and Deserialize trait for your types. Here is a simple example using serde_derive and serde_json:

use serde_hex::{SerHex,StrictPfx,CompactPfx};

struct Foo {
    #[serde(with = "SerHex::<StrictPfx>")]
    bar: [u8;4],
    #[serde(with = "SerHex::<CompactPfx>")]
    bin: u64

fn it_works() {
    let foo = Foo { bar: [0,1,2,3], bin: 16 };
    let ser = serde_json::to_string(&foo).unwrap();
    let exp = r#"{"bar":"0x00010203","bin":"0x10"}"#;

SerHex is automatically implemented for all unsigned integer types, and all Strict variants are implemented for arrays of [T;1] through [T;64] (where T: SerHex of course). We skip default impls for arrays of length zero, as well as signed integers & floats, since there isn't any particularly intuitive way to represent these values.

This crate provides a number of helpful macros for implementing SerHex on common patterns. If none of the macros suit your needs, a number of utility functions are also provided to make implementing custom variations as painless as possible.


Check out the widely used hex crate if you are just looking for generic hexadecimal conversion traits. This crate is intended fairly specifically for customizeable serde interop, and the generic traits of the hex crate should be preferred if that isn't what you are looking for.


Licensed under either of

at your option.


Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.