5

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())
}
amin
  • 3,672
  • 5
  • 33
  • 61
  • Since you already know about [`i32::to_be_bytes`](https://doc.rust-lang.org/std/primitive.i32.html#method.to_be_bytes), why not use [`i32::from_be_bytes`](https://doc.rust-lang.org/std/primitive.i32.html#method.from_be_bytes)? – vallentin Feb 24 '21 at 10:45
  • Duplicate: [How can I convert a buffer of a slice of bytes (&\[u8\]) to an integer?](https://stackoverflow.com/questions/29307474/how-can-i-convert-a-buffer-of-a-slice-of-bytes-u8-to-an-integer) – vallentin Feb 24 '21 at 10:46

1 Answers1

3

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

Netwave
  • 40,134
  • 6
  • 50
  • 93