Debian Codegraph @

src/ImathTest/testToFloat.cpp

raw
1 //
2 // SPDX-License-Identifier: BSD-3-Clause
3 // Copyright Contributors to the OpenEXR Project.
4 //
5
6 #ifdef NDEBUG
7 # undef NDEBUG
8 #endif
9
10 #include <assert.h>
11 #include <cmath>
12 #include <half.h>
13 #include <iomanip>
14 #include <iostream>
15
16 using namespace std;
17
18 //
19 // This test uses the code that generates the toFLoat.h header to
20 // validate the the tabel values are correct.
21 //
22
23 //---------------------------------------------------
24 // Interpret an unsigned short bit pattern as a half,
25 // and convert that half to the corresponding float's
26 // bit pattern.
27 //---------------------------------------------------
28
29 unsigned int
30 halfToFloat (unsigned short y)
31 {
32
33 int s = (y >> 15) & 0x00000001;
34 int e = (y >> 10) & 0x0000001f;
35 int m = y & 0x000003ff;
36
37 if (e == 0)
38 {
39 if (m == 0)
40 {
41 //
42 // Plus or minus zero
43 //
44
45 return s << 31;
46 }
47 else
48 {
49 //
50 // Denormalized number -- renormalize it
51 //
52
53 while (!(m & 0x00000400))
54 {
55 m <<= 1;
56 e -= 1;
57 }
58
59 e += 1;
60 m &= ~0x00000400;
61 }
62 }
63 else if (e == 31)
64 {
65 if (m == 0)
66 {
67 //
68 // Positive or negative infinity
69 //
70
71 return (s << 31) | 0x7f800000;
72 }
73 else
74 {
75 //
76 // Nan -- preserve sign and significand bits
77 //
78
79 return (s << 31) | 0x7f800000 | (m << 13);
80 }
81 }
82
83 //
84 // Normalized number
85 //
86
87 e = e + (127 - 15);
88 m = m << 13;
89
90 //
91 // Assemble s, e and m.
92 //
93
94 return (s << 31) | (e << 23) | m;
95 }
96
97
98
99 void
100 testToFloat()
101 {
102 std::cout << "running testToFloat" << std::endl;
103
104 constexpr int iMax = (1 << 16);
105
106 //
107 // for each 16-bit bit pattern...
108 //
109
110 for (unsigned int s = 0; s < iMax; s++)
111 {
112 half hs(half::FromBits, static_cast<unsigned short>(s));
113 assert (hs.bits() == s);
114
115 //
116 // cast these bits to a float, using the cast-to-float
117 // operator.
118 //
119
120 float f = float (hs); // = _toFloat[s]
121
122 //
123 // Cast that float back to a half.
124 //
125
126 half h = half (f);
127
128 //
129 // halfToFloat() above is what generated the _toFloat table.
130 // The i value return is the integer bit pattern of the corresponding
131 // float.
132 //
133
134 half::uif uif;
135 uif.i = halfToFloat (s);
136
137 //
138 // Equality operators fail for inf and nan, so handle them
139 // specially.
140 //
141
142 if (isnan (f))
143 {
144 assert (h.isNan());
145 assert (isnan (uif.f));
146 }
147 else if (isinf (f))
148 {
149 assert (h.isInfinity());
150 assert (isinf (uif.f));
151 }
152 else
153 {
154 assert (f == uif.f);
155 }
156 }
157
158 std::cout << "ok" << std::endl;
159 }