pu369com

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

其实代码最后一行实现了同样功能,但可以用来学习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

posted on 2021-08-25 16:04  pu369com  阅读(607)  评论(0编辑  收藏  举报

导航