rcx

miscellaneous C library
git clone git://git.rr3.xyz/rcx
Log | Files | Refs | README | LICENSE

commit c767da3aab656bf85f3ec956c5037a786c8d343e
parent 3260a7d245b9f6f9b764c4cc47cb029b93a67f46
Author: Robert Russell <robert@rr3.xyz>
Date:   Sun, 12 Jan 2025 23:52:36 -0800

Add floored division

Diffstat:
Minc/bits.h | 36++++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+), 0 deletions(-)

diff --git a/inc/bits.h b/inc/bits.h @@ -1,5 +1,6 @@ #pragma once +#include <stdbool.h> #include <string.h> #include "def.h" @@ -413,6 +414,41 @@ r_muls64(i64 *h, u64 *l, i64 x, i64 y) { } +/* ----- Floor division ----- */ + +static inline void +r_divs8(i8 *q, i8 *r, i8 x, i8 y) { + i8 qq = x / y, rr = x % y; + bool neg = (x < 0) ^ (y < 0); + *q = qq - ((rr != 0) & neg); + *r = neg ? rr + y : rr; +} + +static inline void +r_divs16(i16 *q, i16 *r, i16 x, i16 y) { + i16 qq = x / y, rr = x % y; + bool neg = (x < 0) ^ (y < 0); + *q = qq - ((rr != 0) & neg); + *r = neg ? rr + y : rr; +} + +static inline void +r_divs32(i32 *q, i32 *r, i32 x, i32 y) { + i32 qq = x / y, rr = x % y; + bool neg = (x < 0) ^ (y < 0); + *q = qq - ((rr != 0) & neg); + *r = neg ? rr + y : rr; +} + +static inline void +r_divs64(i64 *q, i64 *r, i64 x, i64 y) { + i64 qq = x / y, rr = x % y; + bool neg = (x < 0) ^ (y < 0); + *q = qq - ((rr != 0) & neg); + *r = neg ? rr + y : rr; +} + + /* ----- Byte swaps/reversals ----- */ #ifdef __GNUC__