reading single float binary files
Shiv
shiv@balrog.ece.ucsb.edu
Wed, 2 Aug 2000 09:52:11 -0700 (PDT)
I finally decided to write something in Clean that might be of
help. It is not completely tested but should work with +-Inf, Nan,
+-0, denormalized numbers and regular numbers.
--shiv--
/* The function i32r takes an Int and assumes that it is the
32 bit binary representation of a single float number. It then
converts it to Real and returns it.
*/
i32r :: Int -> Real
i32r n
| expField == 0 && fraction == 0 = ieee_zero
| expField == 0 = ieee_denormalized
| expField == 255 && fraction == 0 = ieee_infinity
| expField == 255 = ieee_nan
| otherwise = ieee_fp
where
sign = if ((n bitand 0x80000000) == 0) 1.0 (~1.0)
expField = (n bitand 0x7f800000) >> 23
fraction = n bitand 0x007fffff
ieee_zero = sign * 0.0
ieee_denormalized = sign * toReal fraction * 2.0 ^ ~(23.0+126.0)
ieee_infinity = sign * 2.0 ^ 1024.0
ieee_nan = sign * 0.0/0.0
ieee_fp = sign * (1.0 + toReal fraction * 2.0 ^ ~23.0)
* 2.0 ^ toReal (expField - 127)