以十六进制表示形式显示u8切片 [英] Show u8 slice in hex representation

查看:502
本文介绍了以十六进制表示形式显示u8切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将& [u8] 转换为十六进制表示。例如 [A9,45,FF,00 ...]



特征 std :: fmt :: UpperHex 没有为切片实现(所以我不能使用 std :: fmt :: format )。 Rust具有 serialize :: hex :: ToHex 特征,它将& [u8] 转换为一个十六进制字符串,但我需要一个带有单独字节的表示。



我可以为& amp; amp; //执行trait UpperHex ; [u8] 我自己,但我不确定这将是多么规范。什么是最规范的方式来做到这一点?

解决方案

Rust 1.26.0及以上



使用格式化程序可以使用:x?debug with hexadecimal integers格式化程序:

  let data = bhello; 
println!({:x?},data);
println!({:X?},data);



  [68,65, 6c,6c,6f] 
[68,65,6C,6C,6F]

它可以与漂亮修饰符结合使用:

  let data = bhello; 
println!({:#x?},data);
println!({:#X?},data);



  [
0x68,
0x65,
0x6c,
0x6c,
0x6f
]
[
0x68,
0x65,
0x6C,
0x6C,
0x6F
]

如果你需要更多的控制或需要支持老版本的Rust,继续阅读。



Rust 1.0 and up



 使用std :: fmt :: Write; 

fn main(){
let mut s = String :: new();
for& byte inHello.as_bytes(){
write!(& mut s,{:X},byte).expect(Unable to write);
}

println!({},s);



$ b

这可以通过实现一种格式化特征( fmt :: Debug fmt :: Display fmt :: LowerHex fmt :: UpperHex 等),并且有一个小构造函数:

 使用std :: fmt; 

struct HexSlice< a>(&'a [u8]);

impl<'a> HexSlice<一> {
新n< T>(数据:&'a T) - > HexSlice<一>
其中T:?Sized + AsRef<>> +'a
{
HexSlice(data.as_ref())
}
}

//你甚至可以选择实现多种特质,比如Lower和UpperHex
impl<'a> fmt :: Display for HexSlice<'a> {
fn fmt(& self,f:& mut fmt :: Formatter) - > fmt :: Result {
用于self.0中的字节{
//决定是否要在这里填充值
write!(f,{:X},byte) ?;

OK(())
}
}

fn main(){
//得到一个`String`
let s = format!({},HexSlice :: new(Hello));

//直接打印
println!({},HexSlice :: new(world));

//与
一起工作HexSlice :: new(Hello); //字符串切片(& str)
HexSlice :: new(bHello); //字节片(& [u8])
HexSlice :: new(&World.to_string()); //引用字符串
HexSlice :: new(& vec![0x00,0x01]); //参考Vec< u8>
}


I need to convert &[u8] to a hex representation. For example [ A9, 45, FF, 00 ... ].

The trait std::fmt::UpperHex is not implemented for slices (so I can't use std::fmt::format). Rust has the serialize::hex::ToHex trait, which converts &[u8] to a hex String, but I need a representation with separate bytes.

I can implement trait UpperHex for &[u8] myself, but I'm not sure how canonical this would be. What is the most canonical way to do this?

解决方案

Rust 1.26.0 and up

The :x? "debug with hexadecimal integers" formatter can be used:

let data = b"hello";
println!("{:x?}", data);
println!("{:X?}", data);

[68, 65, 6c, 6c, 6f]
[68, 65, 6C, 6C, 6F]

It can be combined with the pretty modifier as well:

let data = b"hello";
println!("{:#x?}", data);
println!("{:#X?}", data);

[
    0x68,
    0x65,
    0x6c,
    0x6c,
    0x6f
]
[
    0x68,
    0x65,
    0x6C,
    0x6C,
    0x6F
]

If you need more control or need to support older versions of Rust, keep reading.

Rust 1.0 and up

use std::fmt::Write;

fn main() {
    let mut s = String::new();
    for &byte in "Hello".as_bytes() {
        write!(&mut s, "{:X} ", byte).expect("Unable to write");
    }

    println!("{}", s);
}

This can be fancied up by implementing one of the formatting traits (fmt::Debug, fmt::Display, fmt::LowerHex, fmt::UpperHex, etc.) on a struct and having a little constructor:

use std::fmt;

struct HexSlice<'a>(&'a [u8]);

impl<'a> HexSlice<'a> {
    fn new<T>(data: &'a T) -> HexSlice<'a> 
        where T: ?Sized + AsRef<[u8]> + 'a
    {
        HexSlice(data.as_ref())
    }
}

// You can even choose to implement multiple traits, like Lower and UpperHex
impl<'a> fmt::Display for HexSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for byte in self.0 {
            // Decide if you want to pad out the value here
            write!(f, "{:X} ", byte)?;
        }
        Ok(())
    }
}

fn main() {
    // To get a `String`
    let s = format!("{}", HexSlice::new("Hello"));

    // Or print it directly
    println!("{}", HexSlice::new("world"));

    // Works with 
    HexSlice::new("Hello");              // string slices (&str)
    HexSlice::new(b"Hello");             // byte slices (&[u8])
    HexSlice::new(&"World".to_string()); // References to String
    HexSlice::new(&vec![0x00, 0x01]);    // References to Vec<u8>  
}

这篇关于以十六进制表示形式显示u8切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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