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

相关推荐
容智信息12 小时前
AI Agent(智能体)的输出格式应该从 Markdown 转向 HTML吗?
前端·人工智能·rust·编辑器·html·prompt
Rust研习社20 小时前
Rust Clippy 实用指南:写出更优雅、安全的 Rust 代码
后端·rust·编程语言
yangyongdehao3020 小时前
两天用AI+rust撸了一款本地批量去水印软件,30MB,效果能打
ai作画·rust
nudt_qxx21 小时前
NVIDIA 正式开源cuda-oxide!Rust 编写 CUDA 内核新范式!
rust
小杍随笔2 天前
【Rust桌面革命:Tauri×Dioxus——架构对决、实战拆解与2026选型杀招】
开发语言·架构·rust
whinc2 天前
Rust技术周刊 2026年第17周
后端·rust
whinc2 天前
Rust技术周刊 2026年第18周
后端·rust
whinc2 天前
Rust技术周刊 2026年第16周
后端·rust
星辰徐哥2 天前
Rust异步测试与调试的实践指南
android·java·rust