Module hex

Source
Expand description

Hexadecimal encoding and decoding.


hex provides encoding and decoding of binary data to and from hexadecimal strings. Hexadecimal encoding represents each byte as two hexadecimal digits, making binary data readable and safe for text-based protocols and storage.

§Examples

Basic encoding and decoding:

use hex::{encode, decode};

let data = b"Hello, world!";
let hex_string = encode(data);
println!("Hex: {}", hex_string); // "48656c6c6f2c20776f726c6421"

let decoded = decode(&hex_string).unwrap();
assert_eq!(decoded, data);

Uppercase hex encoding:

use hex::encode_upper;

let data = b"ABC";
let hex_upper = encode_upper(data);
println!("Upper: {}", hex_upper); // "414243"

Decoding with error handling:

use hex::decode;

// Valid hex string
let valid = decode("48656c6c6f").unwrap();
assert_eq!(valid, b"Hello");

// Invalid hex string (odd length)
let invalid = decode("48656c6c6");
assert!(invalid.is_err());

// Invalid hex characters
let invalid = decode("xyz123");
assert!(invalid.is_err());

Modules§

serde
Hex encoding with serde.

Enums§

FromHexError
The error type for decoding a hex string into Vec<u8> or [u8; N].

Traits§

FromHex
Types that can be decoded from a hex string.
ToHex
Encoding values as hex string.

Functions§

decode
Decodes a hex string into raw bytes.
decode_to_slice
Decode a hex string into a mutable bytes slice.
deserialize
Deserializes a hex string into raw bytes.
encode
Encodes data as hex string using lowercase characters.
encode_to_slice
Encodes some bytes into a mutable slice of bytes.
encode_upper
Encodes data as hex string using uppercase characters.
serialize
Serializes data as hex string using lowercase characters.
serialize_upper
Serializes data as hex string using uppercase characters.