note 37534 added to language.types.float
| From: | rob at xerasystems dot com | Date: | Wed, 19 Nov 2003 01:06:54 +0000 |
| Subject: | note 37534 added to language.types.float | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-60600@lists.php.net to get a copy of this message | ||
Hi,
A colleague and I are using the socket functions to get data from an Alphaserver running OpenVMS. He
writes out a packet of data from the Alpha that contains integers and floats and I pick them up
using my PHP script.
The two functions below take a 4 byte string that has been parsed from the socket buffer and
converts the string to an integer or float.
function cvt2int4($intstr,$int4)
{
// parse the string
$int0 = hexdec(bin2hex(substr($intstr,0,1)));
$int1 = hexdec(bin2hex(substr($intstr,1,1)));
$int2 = hexdec(bin2hex(substr($intstr,2,1)));
$int3 = hexdec(bin2hex(substr($intstr,3,1)));
// convert to an integer
$int4 = $int0*pow(2,0) + $int1*pow(2,8) + $int2*pow(2,16) + $int3*pow(2,24);
}
function cvt2float4($fltstr,$float4)
{
// Parse the string
$float0 = hexdec(bin2hex(substr($fltstr,0,1)));
$float1 = hexdec(bin2hex(substr($fltstr,1,1)));
$float2 = hexdec(bin2hex(substr($fltstr,2,1)));
$float3 = hexdec(bin2hex(substr($fltstr,3,1)));
// Convert to an integer representation
$float4 = $float0*pow(2,0) + $float1*pow(2,8) + $float2*pow(2,16) + $float3*pow(2,24);
// Get the Sign
$sign = ($float4 & 0x80000000) >> 31;
// Get the exponent
$exp = (($float4 & 0x7F800000) >> 23) - 127;
// Get the Mantissa
$mantissa = $float4 & 0x007FFFFF;
// Calculate the float
$sum = 0.0;
for ($i=-23;$i<0;$i++)
{
$value = $mantissa & 1;
$sum = $sum + $value*pow(2,$i)*pow(2,$exp);
$mantissa = $mantissa >> 1;
}
$sum = $sum + 1*pow(2,0)*pow(2,$exp);
if ($sign == 1)
$float4 = $sum*-1;
else
$float4 = $sum;
}
----
Manual Page -- http://www.php.net/manual/en/language.types.float.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+37534
Delete -- http://master.php.net/manage/user-notes.php?action=delete+37534&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+37534&report=yes
Search -- http://master.php.net/manage/user-notes.php