| 177 | } |
| 178 | |
| 179 | uint16_t f32_to_f16(float x) { |
| 180 | uint32_t u; |
| 181 | std::memcpy(&u, &x, 4); |
| 182 | const uint32_t s = (u >> 16) & 0x8000u; |
| 183 | const int e = (int) ((u >> 23) & 0xff) - 127 + 15; |
| 184 | uint32_t m = u & 0x7fffffu; |
| 185 | if (e <= 0) { // subnormal or zero in f16 |
| 186 | if (e < -10) return (uint16_t) s; |
| 187 | m |= 0x800000u; |
| 188 | const int shift = 14 - e; |
| 189 | uint32_t h = m >> shift; |
| 190 | if ((m >> (shift - 1)) & 1u && ((m & ((1u << (shift - 1)) - 1)) || (h & 1u))) ++h; |
| 191 | return (uint16_t) (s | h); |
| 192 | } |
| 193 | if (e >= 31) return (uint16_t) (s | 0x7c00u); |
| 194 | uint32_t h = ((uint32_t) e << 10) | (m >> 13); |
| 195 | if ((m >> 12) & 1u && ((m & 0xfffu) || (h & 1u))) ++h; // nearest, ties to even |
| 196 | return (uint16_t) (s | h); |
| 197 | } |
| 198 | |
| 199 | uint16_t f32_to_bf16(float x) { |
| 200 | uint32_t u; |
no test coverage detected