How to convert bytes to float

I received a vec using modebus protocol, I am sure it is bytes type in rust, how can I convert it to float?
let bytes:Vec=vec![63, 128, 0, 0];
The converted value should be 1.0

f32::from_be_bytes()

5 Likes

You need to take two steps: take 4 bytes from the input as an array of 4 bytes, and then use f32::from_be_bytes to convert the bytes to a float:

    let bytes: Vec<u8> = vec![63, 128, 0, 0];
    let byte_array: [u8; 4] = bytes[0..4].try_into().expect("Needed 4 bytes for a float");
    let float: f32 = f32::from_be_bytes(byte_array);
    println!("{float}")
4 Likes

Taking care that the bytes are in the right order.

3 Likes

In this particular case (Modbus), the specification declares that everything should be big-endian, and the example bytes given are also big-endian.

If the example was [0, 0, 128, 63], I'd first be asking if this really was Modbus or something different, and secondly you'd need to use from_le_bytes instead.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.