caffeine-hal 0.6.6
A Header-Defined Interface c library, it provides the hal layer for the Caffeine framework
Loading...
Searching...
No Matches
cfn_hal_util.h
Go to the documentation of this file.
1
26#ifndef CAFFEINE_HAL_CFN_HAL_UTIL_H
27#define CAFFEINE_HAL_CFN_HAL_UTIL_H
28#include <stdint.h>
29#include <stdbool.h>
30
31/* --- 1. Multi-Byte Reconstruction (Endianness) --- */
32
40static inline int16_t cfn_util_bytes_to_int16_le(uint8_t msb, uint8_t lsb)
41{
42 /* Use 32-bit unsigned math internally to prevent signed promotion during shifts */
43 const uint32_t COMBINED = ((uint32_t) msb << 8U) | (uint32_t) lsb;
44 return (int16_t) COMBINED;
45}
46
55static inline uint32_t cfn_util_bytes_to_uint32_le(uint8_t b3, uint8_t b2, uint8_t b1, uint8_t b0)
56{
57 return ((uint32_t) b3 << 24U) | ((uint32_t) b2 << 16U) | ((uint32_t) b1 << 8U) | (uint32_t) b0;
58}
59
68static inline int32_t cfn_util_bytes_to_int32_be(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3)
69{
70 const uint32_t COMBINED = ((uint32_t) b0 << 24U) | ((uint32_t) b1 << 16U) | ((uint32_t) b2 << 8U) | (uint32_t) b3;
71 return (int32_t) COMBINED;
72}
73
74/* --- 2. Bitwise Manipulation (Explicit Logic) --- */
75
83static inline uint32_t cfn_util_extract_field(uint32_t val, uint32_t mask, uint32_t shift)
84{
85 /* Mask first, then shift down so the result fits in the smallest possible type */
86 return (uint32_t) ((val & mask) >> shift);
87}
88
95static inline bool cfn_util_bit_is_set(uint8_t reg_val, uint8_t bit_mask)
96{
97 return (bool) ((reg_val & bit_mask) != 0U);
98}
99
100/* --- 3. Saturated & Safe Arithmetic --- */
101
109static inline int16_t cfn_util_sat_add_s16(int16_t a, int16_t b)
110{
111 const int32_t RESULT = (int32_t) a + (int32_t) b;
112 int16_t out;
113 if (RESULT > 32767)
114 {
115 out = 32767;
116 }
117 else if (RESULT < -32768)
118 {
119 out = -32768;
120 }
121 else
122 {
123 out = (int16_t) RESULT;
124 }
125 return out;
126}
127
135static inline float cfn_util_clamp_f32(float val, float min, float max)
136{
137 float res = val;
138 if (val < min)
139 {
140 res = min;
141 }
142 else if (val > max)
143 {
144 res = max;
145 }
146 return res;
147}
148
149/* --- 4. Floating Point Utilities --- */
150
158static inline bool cfn_util_f32_is_equal(float a, float b, float epsilon)
159{
160 float diff = a - b;
161 if (diff < 0.0F)
162 {
163 diff = -diff;
164 }
165 return (bool) (diff <= epsilon);
166}
167
168/* --- 5. Conversion Utilities --- */
169
176static inline int16_t cfn_util_f32_to_q15(float val)
177{
178 const float SCALED = val * 32767.0F;
179 return (int16_t) SCALED;
180}
181
187static inline uint8_t cfn_util_get_msb16(uint16_t val)
188{
189 return (uint8_t) (((uint32_t) val >> 8U) & 0xFFU);
190}
191
197static inline uint8_t cfn_util_get_lsb16(uint16_t val)
198{
199 return (uint8_t) ((uint32_t) val & 0xFFU);
200}
201
202#endif // CAFFEINE_HAL_CFN_HAL_UTIL_H