--!strict --!native --!optimize 2 -- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. local Half = {} local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local function toFloat(h: number): number local s = if h >= 32768 then -1 else 1 local e = band(rshift(h, 10), 31) local m = band(h, 1023) if e == 0 then return s * m * 2 ^ -24 elseif e == 31 then return if m == 0 then s * math.huge else 0 / 0 end return s * (1024 + m) * 2 ^ (e - 25) end Half.toFloat = toFloat local TABLE: { [number]: number } = table.create(65536, 0) for h = 0, 65535 do TABLE[h] = toFloat(h) end Half.TABLE = TABLE local scratch = buffer.create(4) function Half.fromFloat(f: number): number if f ~= f then return 0x7E00 end buffer.writef32(scratch, 0, f) local x = buffer.readu32(scratch, 0) local sign = band(rshift(x, 16), 0x8000) local e = band(rshift(x, 23), 0xFF) local m = band(x, 0x7FFFFF) if e == 255 then return bor(sign, 0x7C00) end local ne = e - 112 if ne >= 31 then return bor(sign, 0x7C00) elseif ne <= 0 then if ne < -10 then return sign end m = bor(m, 0x800000) local shift = 14 - ne local hm = rshift(m, shift) local rem = band(m, lshift(1, shift) - 1) local halfway = lshift(1, shift - 1) if rem > halfway or (rem == halfway and band(hm, 1) == 1) then hm += 1 end return sign + hm end local hm = rshift(m, 13) local rem = band(m, 0x1FFF) if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should end return sign + ne * 1024 + hm end return Half