Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何将十六进制字符串转换为u8切片?_Rust - Fatal编程技术网

Rust 如何将十六进制字符串转换为u8切片?

Rust 如何将十六进制字符串转换为u8切片?,rust,Rust,我有一个字符串,看起来像这个“090A0B0C”,我想把它转换成一个切片,看起来像这个[9,10,11,12]。我最好怎么做呢 我不想将单个十六进制字符元组转换为单个整数值。我想将由多个十六进制字符元组组成的字符串转换为多个整数值的片段。您可以使用板条箱进行转换。该函数看起来像是做了您想要的事情: extern crate hex; fn main() { let input = "090A0B0C"; let decoded = hex::decode(

我有一个字符串,看起来像这个
“090A0B0C”
,我想把它转换成一个切片,看起来像这个
[9,10,11,12]
。我最好怎么做呢

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

您可以使用板条箱进行转换。该函数看起来像是做了您想要的事情:

extern crate hex;

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

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

    println!("{:?}", decoded);
}
上面将打印
[9,10,11,12]
。请注意,
decode
返回一个堆分配的
Vec
,如果您想解码到一个数组中,您希望使用该函数,该函数尚未在crates.io或trait上发布:

外部板条箱六角;
使用hex::FromHex;
fn main(){
让输入=“090A0B0C”;
let decoded=::from_hex(输入)。预期(“解码失败”);
println!(“{:?}”,已解码);
}

您也可以自己实现十六进制编码和解码,以避免依赖于
hex
板条箱:

use std::{fmt::Write, num::ParseIntError};

pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
        .collect()
}

pub fn encode_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        write!(&mut s, "{:02x}", b).unwrap();
    }
    s
}
使用std:{fmt::Write,num::parseinteror};
pub fn decode_hex(s:&str)->结果{
(0..s.len())
.步骤(2)
.map(|i | u8::from_str_基数(&s[i..i+2],16))
.collect()
}
pub fn encode_hex(字节:&[u8])->字符串{
设mut s=String::具有_容量(bytes.len()*2);
以字节为单位的for&b{
write!(&mut s,“{:02x}”,b).unwrap();
}
s
}

请注意,如果字符串长度为奇数,则
decode_hex()
函数会中断。我在操场上做了一个活动。

1。我们希望你能自己努力解决这个问题。2.我不认为你会想要获得一个片段,因为那一个不会拥有内容。可能是@Stargateur的重复,与我的问题重叠的部分是在我问了我的问题后编辑的。如果你不依赖
fmt
crater,你的实现会更酷。我遵守
no_std
标志,无法使用任何基于
std
的crates@Nulik但是,即使使用
no_std
,您是否仍然能够使用
core
库?@Seven yes!今天早上发现的。@Miere这个答案的要点是提供两个简单的函数,如果出于某种原因(例如为了减少编译时间)不想使用
hex
板条箱,可以使用这些函数。我不知道我为什么在操场上写这个版本。与
hex
板条箱相比,我的实现是否有任何优势?如果是这样的话,我很乐意把它放在一个新的板条箱里。@Herohtar对字符串的写入总是返回
Ok(())
。我添加了
.unwrap()。
use std::{fmt::Write, num::ParseIntError};

pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
        .collect()
}

pub fn encode_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        write!(&mut s, "{:02x}", b).unwrap();
    }
    s
}