Convert Slice of 0's and 1's to f64

Hey everyone!
I'm quite new to Rust, so be kind if my question sounds a bit weird! So, currently i am building a weather station with an Raspberry Pi.

To do temp and RH measurements i use the AM2302 Sensor. I have written a small driver in Rust for this Sensor, but i'm not quite satisfied.
During the measurements i collect the response values from the Sensor and push those into a vector. The resulting Slice may be look like that:

['0','0','0','1','1','0', .... ] and so on.
Then i do the conversion like this:

        let rh_high = isize::from_str_radix(&bin[RH_HIGH], 2).unwrap();
        let rh_low = isize::from_str_radix(&bin[RH_LOW], 2).unwrap();
        let t_high = isize::from_str_radix(&bin[T_HIGH], 2).unwrap();
        // and so on...

So, the bits are stored as chars, then i convert the String into isize and so on. Okay, it works, the values are correct. But it seems a little bit weird - is there any "better" method, to convert a Vector of Bits into a floating point number?

The Sensor works like that: '1' Values are held about 70usec, '0' are held about 30usec , so you have to wait for every information and store it - currently they get pushed into a vec. May be we can optimize this, also?

Thanks in advance!

In my mind the obvious implementation would capture the incoming value through bit shifting in a single u64 or so. I'm guessing you're not new to programming in general, and the syntax in Rust is the same as in C and alike (fishbones), the name is Shl & friends.

The "so on" part of your question puzzles me. Are you basically storing the 64 bit input as floating point for later calculations, or are these bits in fact a (IEEE-754) floating point representation, in which case f64:from_bits might be best?

2 Likes

Hey,

thanks for your answer , appreciate it! :slight_smile: The doc to Shl helps me further, i think i can work with that. Already seen that, but i come from the 'Javascript World' so only know this concepts from a more theoretical point of view. But with this know how i'll try to make the code 'more embeddedly' :wink:

Good point, i take a look on it. So maybe my description was not that clearful , in fact, the sensor writes 40 Bit on the line (2 Byte humidity, 2 Byte temp and 1 Byte checksum), so i have to store them for later calculations, e.g., the temp has to be divided by another constant regarding to the datasheet or i have to verify the checksum before shipping the values to the database. So, as I think about it now, f64 is not obligatory, f32 may be totally sufficient

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.