Modbus library how to convert result from Vec<u16> to Swapped FP

// use modbus

fn main() { 
    // connection bah bah.
    // values = read_holding_register(1003, 6);
    // Got values: Vec<u16> = [2412, 16334, 5243, 16318, 22020, 0];
    // i want to convert this values to output like this (Swapped FT)
    // Output expected
    // 41003: 0.5978
    // 41004: 
    // 41005: 1.6100
    // 41006: 
    // 41008: 1.4870
}

(Playground)

Something like this?

fn from_fp_swapped(x: &[u16; 2]) -> f32 {
    let bits = (x[1] as u32) << 16 | (x[0] as u32);
    f32::from_bits(bits)
}

values.chunks_exact(2).map(|chunk| from_fp_swapped(chunk.try_into().unwrap()))

You can use from_bits, from_Xe_bytes and to_Xe_bytes to convert between numbers and their byte representation. x can be n, b and l for native, big and little endian.

What's the bit-level format of these values? Merely transmuting pairs of u16s to f32 doesn't yield the results you want, although 2 out of 3 are at least close. Any other combination (swapping words and/or bytes) results in huge or tiny numbers that look nothing like your expected values.

1 Like

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.