libfxd 0.2.dev
A fixed-point library for C++.
Loading...
Searching...
No Matches
casting.hpp
Go to the documentation of this file.
1/*
2 * libfxd - a fixed-point library for C++
3 *
4 * Copyright 2023 Daniel K. O.
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIBFXD_CASTING_HPP
9#define LIBFXD_CASTING_HPP
10
11#include <type_traits>
12
13#include "concepts.hpp"
14
15#include "detail/bias.hpp"
16#include "detail/shift.hpp"
17
18
19namespace fxd {
20
21
23 template<fixed_point Dst,
24 fixed_point Src>
25 [[nodiscard]]
26 constexpr
27 Dst
28 fixed_cast(Src src)
29 noexcept
30 {
31 using SrcRaw = typename Src::raw_type;
32 using DstRaw = typename Dst::raw_type;
33
34 SrcRaw src_raw = src.raw_value;
35 DstRaw dst_raw;
36
37 constexpr int diff = Dst::frac_bits - Src::frac_bits;
38
39 if constexpr (diff < 0) {
40
41 // shifting right
42 if (src_raw < 0) // if negative, add a bias so it rounds up
43 src_raw += detail::make_bias_for(-diff, src_raw);
44
45 // note: we shift using SrcRaw type, to not lose high bits early
46 dst_raw = detail::shr_real(src_raw, -diff);
47
48 } else {
49
50 // shifting left, no rounding happens
51 // note: we shift using DstRaw type, in case it has more bits than SrcRaw
52 dst_raw = detail::shl_real<DstRaw>(src_raw, diff);
53
54 }
55
56 return Dst::from_raw(dst_raw);
57 }
58
59
61 template<int Int,
62 int Frac,
63 typename Raw = detail::select_int_t<Int + Frac>,
64 fixed_point Src>
65 [[nodiscard]]
66 constexpr
67 fixed<Int, Frac, Raw>
68 fixed_cast(Src src)
69 noexcept
70 {
71 return fixed_cast<fixed<Int, Frac, Raw>>(src);
72 }
73
74
76 template<int Int,
77 int Frac,
78 typename Raw = detail::select_uint_t<Int + Frac>,
79 fixed_point Src>
80 [[nodiscard]]
81 constexpr
82 fixed<Int, Frac, Raw>
83 ufixed_cast(Src src)
84 noexcept
85 {
86 return fixed_cast<fixed<Int, Frac, Raw>>(src);
87 }
88
89
90
91 // TODO: add rounding versions
92
93
94}
95
96
97#endif
Concept to match any fxd::fixed
Definition: concepts.hpp:19
This is the namespace where the entire library is defined.
Definition: casting.hpp:19
constexpr Dst fixed_cast(Src src) noexcept
Convert a fixed point to a different type of fixed point.
Definition: casting.hpp:28
constexpr fixed< Int, Frac, Raw > ufixed_cast(Src src) noexcept
Convert a fixed point to a different type of fixed point (unsigned version.)
Definition: casting.hpp:83