首页 > 其他 > 详细

Rust从&[u8] bytes中读取任意类型的整数(如i32, u32等多种类型)

时间:2021-08-25 18:15:56      阅读:11      评论:0      收藏:0      [点我收藏+]

其实代码最后一行实现了同样功能,但可以用来学习trait和macro

use std::convert::TryInto;
pub trait ReadInteger<T> {
    fn from_le_bytes(data: &[u8]) -> T;
    fn from_be_bytes(data: &[u8]) -> T;
}

macro_rules! impl_read_integer {
    ($($t:ty),+) => {
        $(impl ReadInteger<$t> for $t {
            fn from_le_bytes(data: &[u8]) -> $t {
                <$t>::from_le_bytes(data.try_into().unwrap())
            }
            fn from_be_bytes(data: &[u8]) -> $t {
                <$t>::from_be_bytes(data.try_into().unwrap())
            }
        })+
    }
}

impl_read_integer!(u8, i16, i32, u32, i64);

fn read_integer<T: ReadInteger<T>>(data: &[u8]) -> T {
    T::from_le_bytes(&data[..std::mem::size_of::<T>()])
}
fn main(){
let slice = &[1,2,0,0];
let int1 = read_integer::<i32>(slice);
println!("{}",int1);
println!("{}",u32::from_le_bytes([1,2,0,0]));
}

结果输出513

用计算器将513转为二进制并补齐两个8位:0000  0010  0000 0001,则最右边8位是1,左边8位是2

 

参考:https://blog.csdn.net/qq_26373925/article/details/111087884

Rust从&[u8] bytes中读取任意类型的整数(如i32, u32等多种类型)

原文:https://www.cnblogs.com/pu369/p/15185502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!