/
toFloat.cpp
129 lines (104 loc) · 2.56 KB
/
toFloat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//
// SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenEXR Project.
//
//---------------------------------------------------------------------------
//
// toFloat
//
// A program to generate the lookup table for half-to-float
// conversion needed by class half.
// The program loops over all 65536 possible half numbers,
// converts each of them to a float, and prints the result.
//
//---------------------------------------------------------------------------
#include <iomanip>
#include <iostream>
using namespace std;
//---------------------------------------------------
// Interpret an unsigned short bit pattern as a half,
// and convert that half to the corresponding float's
// bit pattern.
//---------------------------------------------------
unsigned int
halfToFloat (unsigned short y)
{
int s = (y >> 15) & 0x00000001;
int e = (y >> 10) & 0x0000001f;
int m = y & 0x000003ff;
if (e == 0)
{
if (m == 0)
{
//
// Plus or minus zero
//
return s << 31;
}
else
{
//
// Denormalized number -- renormalize it
//
while (!(m & 0x00000400))
{
m <<= 1;
e -= 1;
}
e += 1;
m &= ~0x00000400;
}
}
else if (e == 31)
{
if (m == 0)
{
//
// Positive or negative infinity
//
return (s << 31) | 0x7f800000;
}
else
{
//
// Nan -- preserve sign and significand bits
//
return (s << 31) | 0x7f800000 | (m << 13);
}
}
//
// Normalized number
//
e = e + (127 - 15);
m = m << 13;
//
// Assemble s, e and m.
//
return (s << 31) | (e << 23) | m;
}
//---------------------------------------------
// Main - prints the half-to-float lookup table
//---------------------------------------------
int
main ()
{
cout.precision (9);
cout.setf (ios_base::hex, ios_base::basefield);
cout << "//\n"
"// This is an automatically generated file.\n"
"// Do not edit.\n"
"//\n\n";
cout << "{\n ";
const int iMax = (1 << 16);
for (int i = 0; i < iMax; i++)
{
cout << "{0x" << setfill ('0') << setw (8) << halfToFloat (i) << "}, ";
if (i % 4 == 3)
{
cout << "\n";
if (i < iMax - 1) cout << " ";
}
}
cout << "};\n";
return 0;
}