Files
Jungfraujoch/common/to_fixed.h
Filip Leonarski 1757d42182 Initial commit
Signed-off-by: Filip Leonarski <filip.leonarski@psi.ch>
2023-04-06 11:17:59 +02:00

20 lines
811 B
C++

// Copyright (2019-2022) Paul Scherrer Institute
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef JUNGFRAUJOCH_TO_FIXED_H
#define JUNGFRAUJOCH_TO_FIXED_H
#include <cstdint>
#include <cmath>
inline uint16_t to_fixed(double val, uint16_t fractional_bits) {
// If val is result of division by zero, only reasonable value of output is zero (otherwise number could be interpreted improperly)
uint32_t int_val = std::isfinite(val) ? (std::lround(val * (1<<fractional_bits))) : 0;
// It is unlikely (but not impossible), that gain value will be lower than the smallest possible
// Then reciprocal of gain could be more than allowed by data format. Protection is added for this condition
if (int_val > UINT16_MAX) int_val = UINT16_MAX;
return int_val;
}
#endif //JUNGFRAUJOCH_TO_FIXED_H