frac.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2018 Eistec AB
3  *
4  * This file is subject to the terms and conditions of the GNU Lesser
5  * General Public License v2.1. See the file LICENSE in the top level
6  * directory for more details.
7  */
8 
9 #pragma once
10 
43 #include <stdint.h>
44 
45 #ifdef __cplusplus
46 extern "C" {
47 #endif
48 
52 typedef struct {
53  uint32_t frac;
54  uint8_t shift;
55 } frac_t;
56 
65 uint32_t gcd32(uint32_t u, uint32_t v);
66 
80 void frac_init(frac_t *frac, uint32_t num, uint32_t den);
81 
90 static inline uint32_t frac_scale(const frac_t *frac, uint32_t x)
91 {
92  uint32_t scaled = ((uint64_t)frac->frac * x) >> frac->shift;
93  return scaled;
94 }
95 
96 #ifdef __cplusplus
97 }
98 #endif
void frac_init(frac_t *frac, uint32_t num, uint32_t den)
Initialize frac_t struct.
static uint32_t frac_scale(const frac_t *frac, uint32_t x)
Scale a 32 bit integer by a 32/32 rational number.
Definition: frac.h:90
uint32_t gcd32(uint32_t u, uint32_t v)
Compute greatest common divisor of u and v.
frac descriptor for fraction consisting of two 32 bit integers
Definition: frac.h:52
uint32_t frac
fraction
Definition: frac.h:53
uint8_t shift
exponent
Definition: frac.h:54