Here’s a conversion from Single to Half
Function Float32ToFloat16(d as single) As Int16
dim mb1 as new MemoryBlock(4)
dim mb2 as new MemoryBlock(2)
dim result as Int16
mb1.LittleEndian= false
mb2.LittleEndian= false
mb1.SingleValue(0)= d
// sign bit
mb2.byte(0) = mb1.byte(0) AND &h80
// exponent
dim exp as integer
exp = mb1.Int16Value(0) AND &h7f80 // bits 2-9 of 16
exp = bitwise.ShiftRight(exp, 7)
if exp<> 0 then
exp= exp - 127 // bias for single
exp = exp mod 16
exp= exp + 15 //bias for half
exp = exp AND &h1F // only need 5 significant bits
exp = bitwise.ShiftLeft(exp, 2) // bits 2-6 of 8
mb2.byte(0) = mb2.byte(0) OR exp
end
// mantissa
dim man as integer
man = mb1.Int32Value(0) AND &h7FFFFF
man = ShiftRight(man, 13) // only need first 10 bits
mb2.Int16Value(0) = mb2.Int16Value(0) OR man
result = mb2.Int16Value(0)
return result
End Function