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]);

相关推荐
红尘散仙4 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
红尘散仙4 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
codealy15 小时前
Rust 核心理论与内存安全(一)
后端·安全·rust
土豆.exe16 小时前
IfAI v0.5.0 深度技术解析:120,000 行 Rust 打造的 AI-Native 编辑器
rust·编辑器·ai-native
咸甜适中17 小时前
rust语言学习笔记Trait之 AsRef 和 AsMut(引用转换)
笔记·学习·rust
XD74297163617 小时前
科技早报晚报|2026年5月18日:Agent 原生语言、代码语义图谱与 Rust 数据层,今天更值得跟进的 3 个技术机会
开发语言·科技·rust·科技新闻·开发者工具·ai工程
yezipi耶不耶17 小时前
讲讲 RTMate (WebSocket as A Service)中的消息的发布订阅机制
websocket·网络协议·rust
五月君_1 天前
Bun v1.3.14 发布,Rust 版即将进 Claude Code 内测,下一版可能就告别 Zig
开发语言·后端·rust
techdashen1 天前
深入 Rust enum 的内存世界
开发语言·后端·rust
techdashen1 天前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust