feature(round): Added rounding library.

The first features are:
1) Floor'ing and Ceil'ing to the next value of a specific stepping
2) Floor'ing and Ceil'ing to the next power of 2.
This commit is contained in:
Eric-Paul Ickhorn 2024-05-23 01:12:36 +02:00
parent a5e78dca9a
commit f77dd2b23a
1 changed files with 54 additions and 0 deletions

54
inc-c/ufn/ufn_round.h Normal file
View File

@ -0,0 +1,54 @@
#ifndef UFN_ROUND_H
#define UFN_ROUND_H
#include <stdint.h>
int64_t ufn_floor_i64(int64_t value, int64_t stepping);
int64_t ufn_ceil_i64(int64_t value, int64_t stepping);
uint64_t ufn_floor_pow2(uint64_t value);
uint64_t ufn_ceil_pow2(uint64_t value);
#ifdef UFN_IMPLEMENTATION
int64_t ufn_floor_i64(int64_t value, int64_t stepping)
{
return value - (value % stepping);
}
int64_t ufn_ceil_i64(int64_t value, int64_t stepping)
{
return ufn_floor_i64(value, stepping) + stepping;
}
uint64_t ufn_floor_pow2(uint64_t value)
{
// Find highest-priority bit which is 1
int8_t bit_index = 63;
while(bit_index >= 0)
{
if(value & (1 << bit_index))
{
break;
}
--bit_index;
}
return 1 << bit_index;
}
uint64_t ufn_ceil_pow2(uint64_t value)
{
uint64_t floored = ufn_floor_pow2(value);
if(value == floored)
{
return value;
}
return floored * 2;
}
#endif // UFN_IMPLEMENTATION
#endif // UFN_ROUND_H