Skip to content

Commit d65fbf3

Browse files
committed
sys: util: add a MAP_VALUE to change a value range
This permits to make a computation in a larger range to gain precision: int32_t tmp_in = MAP_VALUE(in, -100, 100, INT32_MIN, INT32_MAX); Or convert between two unit systems: uint32_t fahrenheit = MAP_VALUE(celsius, 0, 100, 32, 212); Signed-off-by: Josuah Demangeon <me@josuah.net>
1 parent 408884d commit d65fbf3

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

include/zephyr/sys/util.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,21 @@ extern "C" {
445445
*/
446446
#define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
447447

448+
/**
449+
* @brief Map a value from one scale to another.
450+
*
451+
* A value of an input range is mappedto a value of an output range.
452+
* The ranges are described by their min and max values.
453+
*
454+
* @param i The value to convert from the input range to the output range.
455+
* @param imin The minimum value of the input range.
456+
* @param imax The maximum value of the input range.
457+
* @param omin The minimum value of the output range.
458+
* @param omax The maximum value of the output range.
459+
*/
460+
#define MAP_VALUE(i, imin, imax, omin, omax) \
461+
(((i) - (imin)) * (omin - omax) / ((imax) - (imin)) + (omin))
462+
448463
/**
449464
* @brief Is @p x a power of two?
450465
* @param x value to check

0 commit comments

Comments
 (0)