mockup/util übernommen (fixed point, rectangle)
[hackover2013-badge-firmware.git] / badge / util / fixed_point.h
1 #ifndef INCLUDED_FIXED_POINT_H
2 #define INCLUDED_FIXED_POINT_H
3
4 #include <stdint.h>
5 #include <stdbool.h>
6
7 /* Unterstes Byte als Nachkomma. 16 Bit Nutzlast! Sonst geht Multiplikation flöten. */
8 typedef struct { int32_t data; } fixed_point;
9
10 static inline fixed_point fixed_point_add(fixed_point x, fixed_point y) { fixed_point r = { x.data + y.data }; return r; }
11 static inline fixed_point fixed_point_sub(fixed_point x, fixed_point y) { fixed_point r = { x.data - y.data }; return r; }
12 static inline fixed_point fixed_point_mul(fixed_point x, fixed_point y) { fixed_point r = { x.data * y.data / 256 }; return r; }
13 static inline fixed_point fixed_point_div(fixed_point x, fixed_point y) { fixed_point r = { (x.data * 256) / y.data }; return r; }
14
15 static inline fixed_point fixed_point_neg(fixed_point x) { fixed_point r = { -x.data }; return r; }
16 static inline fixed_point fixed_point_abs(fixed_point x) { fixed_point r = { x.data < 0 ? -x.data : x.data }; return r; }
17
18 static inline bool fixed_point_lt(fixed_point x, fixed_point y) { return x.data < y.data; }
19 static inline bool fixed_point_gt(fixed_point x, fixed_point y) { return x.data > y.data; }
20 static inline bool fixed_point_le(fixed_point x, fixed_point y) { return x.data <= y.data; }
21 static inline bool fixed_point_ge(fixed_point x, fixed_point y) { return x.data >= y.data; }
22 static inline bool fixed_point_eq(fixed_point x, fixed_point y) { return x.data == y.data; }
23 static inline bool fixed_point_ne(fixed_point x, fixed_point y) { return x.data != y.data; }
24
25 #define FIXED_POINT_I(x, y) { ((x) * 256) + ((y) * 256 / 1000) }
26
27 static inline fixed_point FIXED_POINT(unsigned x, unsigned y) {
28 fixed_point r = { ((int) x * 256) + ((int) y * 256 / 1000) };
29 return r;
30 }
31
32 static inline int fixed_point_cast_int(fixed_point x) { return x.data / 256; }
33
34 static inline fixed_point fixed_point_min(fixed_point x, fixed_point y) { return fixed_point_lt(x, y) ? x : y; }
35 static inline fixed_point fixed_point_max(fixed_point x, fixed_point y) { return fixed_point_gt(x, y) ? x : y; }
36
37 #endif
This page took 0.060578 seconds and 5 git commands to generate.