Rust常用库之处理hex数据hex-literal

文章目录

Rust常用库之处理hex数据hex-literal

需求

十六进制数据解码为raw data(vec)、将字节序列转换为十六进制表示

hex-literal

官方:https://docs.rs/releases/search?query=hex_literal

This crate provides the hex! macro for converting hexadecimal string literals to a byte array at compile time.

It accepts the following characters in the input string:

  • '0'...'9', 'a'...'f', 'A'...'F' --- hex characters which will be used in construction of the output byte array
  • ' ', '\r', '\n', '\t' --- formatting characters which will be ignored

Examples

const DATA: [u8; 4] = hex!("01020304");

assert_eq!(DATA, [1, 2, 3, 4]);

assert_eq!(hex!("a1 b2 c3 d4"), [0xA1, 0xB2, 0xC3, 0xD4]);

assert_eq!(hex!("E5 E6 90 92"), [0xE5, 0xE6, 0x90, 0x92]);

assert_eq!(hex!("0a0B 0C0d"), [10, 11, 12, 13]);

let bytes = hex!("

00010203 04050607

08090a0b 0c0d0e0f

");

assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);

assert_eq!(hex!("0a0B // 0c0d line comments"), [10, 11]);

assert_eq!(hex!("0a0B // line comments

0c0d"), [10, 11, 12, 13]);

assert_eq!(hex!("0a0B /* block comments / 0c0d"), [10, 11, 12, 13]);
assert_eq!(hex!("0a0B /
multi-line

block comments

*/ 0c0d"), [10, 11, 12, 13]);

相关推荐
Rust研习社1 天前
Once、OnceCell、OnceLock:Rust 一次性初始化终极指南
后端·rust·编程语言
Rust研习社1 天前
从入门到实践:Rust 异步编程完全指南
开发语言·后端·rust
Rust研习社1 天前
Rust Pin 解析:核心原理与异步编程实践
开发语言·后端·rust
圆山猫1 天前
[AI] [Linux] 教我编一个启用rust的riscv kernel用于qemu启动
linux·ai·rust
代码羊羊1 天前
Rust-特征trait和特征对象
服务器·网络·rust
圆山猫1 天前
[AI] [Linux] 教我用rust写一个GPIO驱动
linux·rust
DevilSeagull2 天前
Rust 结构体详解:从定义到实例化的指南
开发语言·算法·安全·rust
圆山猫2 天前
[AI] [RISCV] 用 Rust 写一个 RISC-V BootROM:从 QEMU 到真实硬件
开发语言·rust·risc-v
AI首席情报员_阿布2 天前
Numa:用 Rust 从零造一个 DNS 解析器,顺手解决了开发者最头疼的几件事
人工智能·rust·dns
Rust研习社2 天前
Rust 多线程从入门到实战
开发语言·后端·rust