List Info

Thread: note 51271 deleted from language.types.float by bjori




note 51271 deleted from language.types.float by bjori
user name
2007-09-27 07:32:13
Note Submitter: vic at liveforspeed dot net 

----

I couldn't find any function to read a float from a file
written by C++ (PC?) for example. This format has reversed
byte order compared to PHP and in addition, there is just no
bin2float function afaik, so I wrote my own binary float 2
usable php float import function.
It does not support SNaN and QNaN values though (didn't need
to check for them for my purpose).
Hope it'll be to some use for some:

<?
// $bin must be 4 bytes, MSB first (Most Significant Byte)
function bin2float ($bin) {
    $float = (float) 0;

    // Read Exponent and Sign (+/-)
    $exponent = ord ($bin);
    if ($sign = $exponent & 128) $exponent -= 128;
    $exponent <<= 1;

    // Read the remaining bit for Exponent and loop through
Mantissa, calculating the Fraction
    $fraction = (float) 1;
    $div = 1;
    for ($x=2; $x>=0; $x--) {
        $byte = ord ($bin{$x});
        for ($y=7; $y>=0; $y--) {
          if ($x==2 && $y==7) {
            if ($byte & (1 << $y)) $exponent +=
1;
          } else {
            $div *= 0.5;
            if ($byte & (1 << $y)) $fraction +=
$div;
          }
        }
    }

    // 0 value check
    if (!$exponent && $fraction == 1) return 0;

    // Final calc, returning the converted float
    $exponent -= 127;

    $float = pow (2, $exponent) * $fraction;
    if ($sign) $float = -($float);

    return $float;
}

echo bin2float (chr (0xb1).chr (0x5c).chr (0xbc).chr
(0x41))."n";
echo bin2float (chr (0x00).chr (0x18).chr (0x5c).chr
(0x3f))."n";
echo bin2float (chr (0).chr (0).chr (160).chr
(193))."n";
echo bin2float (chr (0).chr (0).chr (0).chr (0));
?>

returns:
23.5452594757
0.859741210938
-20
0

(to understand the workings of floats better, I found http://
www.randelshofer.ch/fhw/gri/float.html to be a good
reference)

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1]

about | contact  Other archives ( Real Estate discussion Medical topics )