Version 0 of IEEE binary float to string conversion

Updated 2000-04-27 09:41:40

From a post in news:comp.lang.tcl :

Floating point values are usually transferred in IEEE format. I have written the following code to read an IEEE float value for the case that your machine doesn't use IEEE natively.

 proc IEEE2float {data byteorder} {
    if {$byteorder == 0} {
        set code [binary scan $data cccc se1 e2f1 f2 f3]
    } else {
        set code [binary scan $data cccc f3 f2 e2f1 se1]
    }

    set se1  [expr {($se1 + 0x100) % 0x100}]
    set e2f1 [expr {($e2f1 + 0x100) % 0x100}]
    set f2   [expr {($f2 + 0x100) % 0x100}]
    set f3   [expr {($f3 + 0x100) % 0x100}]

    set sign [expr {$se1 >> 7}]
    set exponent [expr {(($se1 & 0x7f) << 1 | ($e2f1 >> 7))}]
    set f1 [expr {$e2f1 & 0x7f}]

    set fraction [expr {double($f1)*0.0078125 + \
            double($f2)*3.0517578125e-05 + \
            double($f3)*1.19209289550781e-07}]

    set res [expr {($sign ? -1. : 1.) * \
            pow(2.,double($exponent-127)) * \
            (1. + $fraction)}]
    return $res
 }

It expects a binary buffer containing an IEEE number and the byte order the number is in (0 for big-endian and 1 for little-endian).

3fa22435 yields 1.2667299509 (big-endian) or 6.1330860035e-07 (little).

 + Frank Pilhofer                        [email protected]   +
 |                                      http://www.uni-frankfurt.de/~fp/