NEP 4.3.0
NetCDF Expansion Pack
Loading...
Searching...
No Matches
float16_conv.h
Go to the documentation of this file.
1
12#ifndef FLOAT16_CONV_H
13#define FLOAT16_CONV_H
14
15#include "nxcdf/nxcdf.h"
16#include <stdint.h>
17#include <string.h>
18
20#define F16_FILL_IN 9.99e+20f
21
23#define F16_REL_ERR_MAX 0.00048828125
24
28#define F16_ABS_ERR_MAX 2.9802322387695312e-08
29
42static inline uint16_t
44{
45 uint32_t u, mag, sig, mant, rem;
46 uint16_t sign;
47 int e, shift;
48
49 memcpy(&u, &f, sizeof(u));
50 mag = u & 0x7fffffffu;
51 sign = (uint16_t)((u >> 16) & 0x8000u);
52
53 /* NaN: keep the top payload bits and force the quiet bit. */
54 if (mag > 0x7f800000u)
55 return (uint16_t)(sign | 0x7c00u | ((u >> 13) & 0x03ffu) | 0x0200u);
56
57 /* Infinity stays infinity. */
58 if (mag == 0x7f800000u)
59 return (uint16_t)(sign | 0x7c00u);
60
61 /* Finite magnitudes of 65520 or more overflow to infinity (the
62 * tie at 65520 rounds to even, which is infinity). */
63 if (mag >= 0x477ff000u) /* 65520.0f */
64 return (uint16_t)(sign | 0x7c00u);
65
66 e = (int)(mag >> 23);
67
68 /* Normal result: rebase the exponent and round the significand to
69 * 10 bits, ties to even. A carry out of the mantissa ripples into
70 * the exponent, which is correct. */
71 if (e >= 113) {
72 uint32_t m = mag & 0x7fffffu;
73 uint32_t rounded = (m + 0x0fffu + ((m >> 13) & 1u)) >> 13;
74
75 return (uint16_t)(sign | (uint16_t)(((e - 112) << 10) + rounded));
76 }
77
78 /* Subnormal result or signed zero. */
79 shift = 126 - e;
80 if (shift >= 32)
81 return sign;
82 sig = 0x800000u | (mag & 0x7fffffu);
83 mant = sig >> shift;
84 rem = sig & ((1u << shift) - 1u);
85 if (rem > (1u << (shift - 1)) || (rem == (1u << (shift - 1)) && (mant & 1u)))
86 mant++;
87 return (uint16_t)(sign | (uint16_t)mant);
88}
89
96static inline float
98{
99 uint32_t sign = (uint32_t)(h & 0x8000u) << 16;
100 uint32_t e = (h >> 10) & 0x1fu;
101 uint32_t m = h & 0x03ffu;
102 uint32_t u;
103 float f;
104
105 if (e == 0) {
106 if (!m) {
107 u = sign;
108 } else {
109 e = 1;
110 while (!(m & 0x400u)) { m <<= 1; e--; }
111 m &= 0x3ffu;
112 u = sign | ((uint32_t)(e + 112) << 23) | (m << 13);
113 }
114 } else if (e == 31) {
115 u = sign | 0x7f800000u | (m << 13);
116 } else {
117 u = sign | ((e + 112u) << 23) | (m << 13);
118 }
119 memcpy(&f, &u, sizeof(f));
120 return f;
121}
122
123#endif /* FLOAT16_CONV_H */
static float float16_to_float(uint16_t h)
Convert an IEEE 754 binary16 bit pattern to float32 (exact).
Definition float16_conv.h:97
static uint16_t float_to_float16(float f)
Convert a float32 to an IEEE 754 binary16 bit pattern, round to nearest, ties to even.
Definition float16_conv.h:43
Public API for the nxCDF UDF backend.