note 51271 added to language.types.float

From: Date: Fri, 25 Mar 2005 08:48:42 +0000
Subject: note 51271 added to language.types.float
Groups: php.notes 
Request: Send a blank email to php-notes+get-86934@lists.php.net to get a copy of this message
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{3}); 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) ---- Manual Page -- http://www.php.net/manual/en/language.types.float.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51271 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51271&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51271&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51271&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51271&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51271&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51271&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#86934) next »