i have writed a test for u32 convert to &[u8] and &[u8] convert to u32.
like this:
pub struct ByteBuf {
bytes: Vec<u8>,//bytes数据
index: usize,//读写指针
}
impl ByteBuf{
pub fn push_u32(&mut self, i: u32) {
unsafe {
let byte = transmute::<u32, [u8; 4]>(i);
for i in &byte {
self.bytes.push(*i);
}
}
}
pub fn read_u32(&mut self) -> Result<u32,&str> {
if self.bytes.len()-self.index<4{
return Err("NotEnough");
}
let b = &self.bytes[self.index..=self.index + 3];
self.index += 4;
let mut int = 0;
unsafe {
let mut byte: [u8; 4] = [0; 4];
for i in 0..3 {
byte[i] = b[i];
}
int = transmute::<[u8; 4], u32>(byte);
}
Ok(int)
}
}
i wanna call push_u32 fun,then call read_u32 for get the same number.
but when the number of i call push_u32 if the u32 value I passed in was too large, read_u32 got the wrong result.
for example:
then i call push_u32,and passed in a 1011000001,the bytes's values is[193,162,66,60],
it's not right values,if i call read_u32,i will get 4367041,not 1011000001.
if i call push_u32 10110001and passed in 10110001,the read_u32 will give me 10110001.
why? 1011000001 didn't spill over,but can not get right result.
pls help me.thanks