Search code examples
rustunsafe

How to convert a 4 element &[u8] into i32?


I have an i32 that i pass to my keyvalue database.

let a = 1234i32;
db.put(&a.to_be_bytes());

But i get it back as &[u8], how to convert it back to i32?


update: this example pretty much does what i want.

use std::convert::TryInto;

fn read_be_i32(input: &[u8]) -> i32 {
    i32::from_be_bytes(input.try_into().unwrap())
}

Solution

  • Use 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);
    }
    

    Playground