如何将十六进制字符串转换为 u8 切片? [英] How can I convert a hex string to a u8 slice?

查看:65
本文介绍了如何将十六进制字符串转换为 u8 切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的字符串 "090A0B0C" 我想把它转换成一个看起来像这样的切片 [9, 10, 11, 12].我最好怎么做?

I have a string that looks like this "090A0B0C" and I would like to convert it to a slice that looks something like this [9, 10, 11, 12]. How would I best go about doing that?

我不想将单个十六进制字符元组转换为单个整数值.我想将由多个十六进制字符元组组成的字符串转换为多个整数值的切片.

I don't want to convert a single hex char tuple to a single integer value. I want to convert a string consisting of multiple hex char tuples to a slice of multiple integer values.

推荐答案

您可以使用 hex板条箱.decode 函数看起来像你想要的:

You could use the hex crate for that. The decode function looks like it does what you want:

extern crate hex;

fn main() {
    let input = "090A0B0C";

    let decoded = hex::decode(input).expect("Decoding failed");

    println!("{:?}", decoded);
}

上面会打印[9, 10, 11, 12].请注意,decode 返回一个分配给 Vec 的堆,如果您想解码为一个数组,您需要使用 decode_to_slice 函数,尚未在板条箱上发布.ioFromHex 特性:

The above will print [9, 10, 11, 12]. Note that decode returns a heap allocated Vec<u8>, if you want to decode into an array you'd want to use the decode_to_slice function, which is not yet released on crates.io or the FromHex trait:

extern crate hex;

use hex::FromHex;

fn main() {
    let input = "090A0B0C";

    let decoded = <[u8; 4]>::from_hex(input).expect("Decoding failed");

    println!("{:?}", decoded);
}

这篇关于如何将十六进制字符串转换为 u8 切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆