如何将 4 元素 &[u8] 转换为 i32?
How to convert a 4 element &[u8] into i32?
我有一个 i32
传递到我的键值数据库。
let a = 1234i32;
db.put(&a.to_be_bytes());
但我把它恢复为 &[u8]
,如何将它转换回 i32
?
更新:这个例子几乎符合我的要求。
use std::convert::TryInto;
fn read_be_i32(input: &[u8]) -> i32 {
i32::from_be_bytes(input.try_into().unwrap())
}
使用i32::from_be_bytes
and from this answer,TryFrom
:
use std::convert::TryFrom;
fn main() {
let a = 1234i32.to_be_bytes();
let a_ref: &[u8] = &a;
let b = i32::from_be_bytes(<[u8; 4]>::try_from(a_ref).expect("Ups, I did it again..."));
println!("{}", b);
}
我有一个 i32
传递到我的键值数据库。
let a = 1234i32;
db.put(&a.to_be_bytes());
但我把它恢复为 &[u8]
,如何将它转换回 i32
?
更新:这个例子几乎符合我的要求。
use std::convert::TryInto;
fn read_be_i32(input: &[u8]) -> i32 {
i32::from_be_bytes(input.try_into().unwrap())
}
使用i32::from_be_bytes
and from this answer,TryFrom
:
use std::convert::TryFrom;
fn main() {
let a = 1234i32.to_be_bytes();
let a_ref: &[u8] = &a;
let b = i32::from_be_bytes(<[u8; 4]>::try_from(a_ref).expect("Ups, I did it again..."));
println!("{}", b);
}