7f3a3e044afd896cc4a3334a7dafba9b3dccc701
[apps/agl-service-can-low-level.git] / libs / bitfield-c / src / canutil / write.c
1 #include <canutil/write.h>
2 #include <bitfield/bitfield.h>
3 #include <bitfield/8byte.h>
4
5 uint64_t float_to_fixed_point(const float value, const float factor,
6         const float offset) {
7     float raw = (value - offset) / factor;
8     if(raw > 0) {
9         // round up to avoid losing precision when we cast to an int
10         // TODO do we need a way to encode an int back to a signal without any
11         // rounding?
12         raw += 0.5;
13     }
14     return (uint64_t)raw;
15 }
16
17 uint64_t eightbyte_encode_float(float value, uint8_t bit_offset, uint8_t bit_size,
18         float factor, float offset) {
19     uint64_t result = 0;
20     if(!eightbyte_set_bitfield(float_to_fixed_point(value, factor, offset),
21                 bit_offset, bit_size, &result)) {
22         // debug("%f will not fit in a %d bit field", value, bit_size);
23     }
24     return result;
25 }
26
27 uint64_t eightbyte_encode_bool(const bool value, const uint8_t bit_offset,
28         const uint8_t bit_size) {
29     return eightbyte_encode_float(value, bit_offset, bit_size, 1.0, 0);
30 }
31
32 bool bitfield_encode_float(const float value, const uint8_t bit_offset,
33         const uint8_t bit_size, const float factor, const float offset,
34         uint8_t destination[], const uint8_t destination_length) {
35     if(!set_bitfield(float_to_fixed_point(value, factor, offset), bit_offset,
36                 bit_size, destination, destination_length)) {
37         // debug("%f will not fit in a %d bit field", value, bit_size);
38         return false;
39     }
40     return true;
41 }
42
43 bool bitfield_encode_bool(const bool value, const uint8_t bit_offset,
44         const uint8_t bit_size, uint8_t destination[],
45         const uint16_t destination_length) {
46     return bitfield_encode_float(value, bit_offset, bit_size, 1.0, 0,
47             destination, destination_length);
48 }