| 65 | // Converts a IEEE binary32/64 into a binary16. Rounds to nearest with ties to zero |
| 66 | template <typename T> |
| 67 | uint16_t BinaryConverter<T>::ToBinary16(T f_bits) { |
| 68 | // Sign mask for output binary16 |
| 69 | const uint16_t h_sign = uint16_t((f_bits >> (kNumBits - 16)) & 0x8000); |
| 70 | |
| 71 | // Exponent mask for input binary |
| 72 | const T f_exp = f_bits & kExpMask; |
| 73 | // Exponents as signed pre-shifted values for convenience. Here, we need to re-bias the |
| 74 | // exponent for a binary16. If, after re-biasing, the binary16 exponent falls outside of |
| 75 | // the range [1,30] then we need to handle the under/overflow case specially. |
| 76 | const int16_t f_biased_exp = int16_t(f_exp >> kMantNumBits); |
| 77 | const int16_t unbiased_exp = f_biased_exp - kExpBias; |
| 78 | const int16_t h_biased_exp = unbiased_exp + 15; |
| 79 | |
| 80 | // Mantissa mask for input |
| 81 | const T f_mant = f_bits & kMantMask; |
| 82 | |
| 83 | // We define a "rounding bit", which is the most significant bit to be dropped |
| 84 | // (e.g. for a binary32, 0x1000). |
| 85 | constexpr T rounding_bit = T(1) << (kMantNumBits - (10 + 1)); |
| 86 | |
| 87 | // Handle exponent overflow, NaN, and +/-Inf |
| 88 | if (h_biased_exp >= 0x1f) { |
| 89 | // The input is a NaN representation |
| 90 | if (f_exp == kExpMask && f_mant != 0) { |
| 91 | uint16_t h_mant = uint16_t(f_mant >> (kMantNumBits - 10)); |
| 92 | // If the mantissa bit(s) indicating NaN were shifted out, add one back. Otherwise, |
| 93 | // the result would be infinity. |
| 94 | if (h_mant == 0) { |
| 95 | h_mant = 0x1; |
| 96 | } |
| 97 | return uint16_t(h_sign | 0x7c00u | h_mant); |
| 98 | } |
| 99 | |
| 100 | // Clamp to +/-infinity |
| 101 | return uint16_t(h_sign | 0x7c00u); |
| 102 | } |
| 103 | |
| 104 | // Handle exponent underflow, subnormals, and +/-0 |
| 105 | if (h_biased_exp <= 0) { |
| 106 | // If the underflow exceeds the number of bits in a binary16 mantissa (10) then we |
| 107 | // can't round, so just clamp to 0. Note that this also weeds out any input values |
| 108 | // that are subnormal - including +/-0; |
| 109 | if (h_biased_exp < -10) { |
| 110 | return h_sign; |
| 111 | } |
| 112 | |
| 113 | // Convert to a rounded subnormal value starting with the mantissa. Since the input |
| 114 | // input is known to be normal at this point, we need to prepend its implicit leading |
| 115 | // bit - which also necessitates an additional right-shift. |
| 116 | T rounded_mant = (T(1) << kMantNumBits) | f_mant; |
| 117 | rounded_mant >>= (1 - h_biased_exp); |
| 118 | |
| 119 | // Here, we implement rounding to nearest (with ties to even) |
| 120 | // |
| 121 | // By now, our new mantissa has two conceptual ranges: |
| 122 | // - The lower 13 bits, which will be shifted out |
| 123 | // - The upper 10 bits, which will become the binary16's mantissa |
| 124 | // |
nothing calls this directly
no outgoing calls
no test coverage detected