问题描述
我有一个看起来像这样的字符串 "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
函数, 或 FromHex
特性:
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, 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 切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!