IEEE 754 binary32 to binary16, rounding to nearest with ties to even.
Values past the largest half become infinity, values below the smallest subnormal become a signed zero, and a NaN stays a NaN.
37{
38 uint32_t pattern {};
39 std::memcpy(&pattern, &value, sizeof(pattern));
40
41 const uint32_t sign = (pattern >> 16) & 0x8000U;
42 const auto field = static_cast<int32_t>((pattern >> 23) & 0xFFU);
43 uint32_t mantissa = pattern & 0x7FFFFFU;
44
45 if (field == 0xFF) {
46 if (mantissa == 0)
47 return static_cast<uint16_t>(sign | 0x7C00U);
48 return static_cast<uint16_t>(sign | 0x7C00U | 0x200U | (mantissa >> 13));
49 }
50
51 const int32_t exponent = field - 127 + 15;
52 if (exponent >= 0x1F)
53 return static_cast<uint16_t>(sign | 0x7C00U);
54
55 if (exponent <= 0) {
56 if (exponent < -10)
57 return static_cast<uint16_t>(sign);
58 mantissa |= 0x800000U;
59 const auto shift = static_cast<uint32_t>(14 - exponent);
60 uint32_t half = mantissa >> shift;
61 const uint32_t round_bit = 1U << (shift - 1U);
62 if ((mantissa & round_bit) != 0U && ((mantissa & (round_bit - 1U)) != 0U || (half & 1U) != 0U))
63 ++half;
64 return static_cast<uint16_t>(sign | half);
65 }
66
67 uint32_t half = (static_cast<uint32_t>(exponent) << 10) | (mantissa >> 13);
68 const uint32_t remainder = mantissa & 0x1FFFU;
69 if (remainder > 0x1000U || (remainder == 0x1000U && (half & 1U) != 0U))
70 ++half;
71 return static_cast<uint16_t>(sign | half);
72}