hashmismatch / packed_struct.rs

Bit-level packing and unpacking for Rust
MIT License
163 stars 30 forks source link

Possible to store floating/fixed point values? #41

Open thebeekeeper opened 5 years ago

thebeekeeper commented 5 years ago

I've got a somewhat odd, completely custom, CANBUS message format that I'm trying to serialize. It uses fixed point numbers which I'm storing as f32. Is it possible to use this crate for directly packing these values? Here's an example of the kind of thing I'm trying to deal with:

pub struct Status {
   // this is bits 0..13, interpreted as 0.5 psi/bit
   pub downforce: f32,
   pub state: u8,
}

Thanks for the great library! This would have saved me a ton of time debugging in the field if I had found it earlier!

rudib commented 5 years ago

Glad that you've found the library useful!

I'd love to add support for floating points but I'll need to do some reading how various memory-constrained platforms and network protocols handle endianness and floating points, as I'm pretty sure it's an interesting topic.

https://en.wikipedia.org/wiki/Endianness#Floating_point

maugier commented 2 years ago

Hi!

The standard library docs seem to imply that endianness isn't such an issue, and the lib offers straightforward conversion between floats ints, and arrays:

https://doc.rust-lang.org/stable/std/primitive.f32.html#method.from_bits

I think it's reasonable to support floats in a compatible way?

I've looked into implementing float support, but I'm not sure how to proceed. Custom-size floats probably don't make sense, but custom endianness does; should we define wrappers like LsbFloat and MsbFloat, and emit them during codegen, or is it better to reuse the existing Integer wrapper?

mkolopanis commented 1 year ago

I have a use case that would also benefit from being able to use floats with PackedStruct. Any updates on this issue or a way to help get this going?

David-OConnor commented 1 year ago

Any prog on this? Unable to proceed.

Should be equiv to a u32 etc with ::to_be_bytes() etc.