uc_float_spec.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
3  */
4 
7 #include <cmath>
8 
9 namespace uavcan
10 {
11 
12 #if !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION
13 
14 union Fp32
15 {
17  float f;
18 };
19 
20 /*
21  * IEEE754Converter
22  */
24 {
25  /*
26  * https://gist.github.com/rygorous/2156668
27  * Public domain, by Fabian "ryg" Giesen
28  */
29  const Fp32 f32infty = { 255U << 23 };
30  const Fp32 f16infty = { 31U << 23 };
31  const Fp32 magic = { 15U << 23 };
32  const uint32_t sign_mask = 0x80000000U;
33  const uint32_t round_mask = ~0xFFFU;
34 
35  Fp32 in;
36  uint16_t out;
37 
38  in.f = value;
39 
40  uint32_t sign = in.u & sign_mask;
41  in.u ^= sign;
42 
43  if (in.u >= f32infty.u) /* Inf or NaN (all exponent bits set) */
44  {
45  /* NaN->sNaN and Inf->Inf */
46  out = (in.u > f32infty.u) ? 0x7FFFU : 0x7C00U;
47  }
48  else /* (De)normalized number or zero */
49  {
50  in.u &= round_mask;
51  in.f *= magic.f;
52  in.u -= round_mask;
53  if (in.u > f16infty.u)
54  {
55  in.u = f16infty.u; /* Clamp to signed infinity if overflowed */
56  }
57 
58  out = uint16_t(in.u >> 13); /* Take the bits! */
59  }
60 
61  out = uint16_t(out | (sign >> 16));
62 
63  return out;
64 }
65 
67 {
68  /*
69  * https://gist.github.com/rygorous/2144712
70  * Public domain, by Fabian "ryg" Giesen
71  */
72  const Fp32 magic = { (254U - 15U) << 23 };
73  const Fp32 was_infnan = { (127U + 16U) << 23 };
74  Fp32 out;
75 
76  out.u = (value & 0x7FFFU) << 13; /* exponent/mantissa bits */
77  out.f *= magic.f; /* exponent adjust */
78  if (out.f >= was_infnan.f) /* make sure Inf/NaN survive */
79  {
80  out.u |= 255U << 23;
81  }
82  out.u |= (value & 0x8000U) << 16; /* sign bit */
83 
84  return out.f;
85 }
86 
87 #endif // !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION
88 
89 }
uavcan::Fp32::u
uint32_t u
Definition: uc_float_spec.cpp:16
uavcan::uint32_t
std::uint32_t uint32_t
Definition: std.hpp:26
float_spec.hpp
uavcan::IEEE754Converter::halfToNativeIeee
static float halfToNativeIeee(uint16_t value)
Definition: uc_float_spec.cpp:66
uavcan::uint16_t
std::uint16_t uint16_t
Definition: std.hpp:25
uavcan::IEEE754Converter::nativeIeeeToHalf
static uint16_t nativeIeeeToHalf(float value)
Definition: uc_float_spec.cpp:23
uavcan::Fp32::f
float f
Definition: uc_float_spec.cpp:17
build_config.hpp
uavcan::Fp32
Definition: uc_float_spec.cpp:14
uavcan
Definition: libuavcan/libuavcan/include/uavcan/build_config.hpp:204


uavcan_communicator
Author(s):
autogenerated on Fri Dec 13 2024 03:10:03