Here's a PHP test driver and some code I wrote to parse hex strings representing IEEE 32-bit floats. It works. But I have this nagging feeling that there's a really simple, even elegant, way to code this, and I just don't see what it is. So I'm posting here in hopes of learning some new PHP code skills.
IEEE 32-bit floating point consists of a 1-bit sign, an 8-bit excess-127 exponent, and a 24-bit mantissa (leading 1 implied, 23 bits from input).
Thanks in advance for any improvements or discussion about function ieeeConvert in code below.
Stan
<?php
// ****************************
// test hex ieee float conversion
// *****************************
$testCases = array(
'00000000' => 0.0 ,
'3F800000' => 1.0 ,
'B8D1B717' => -0.0001 ,
'C2C7FAE1' => -99.99 ,
'461C4000' => 10000.0);
foreach ($testCases as $hex => $answer) {
echo "Test value = x'$hex'\n";
$calc = ieeeConvert($hex, 4);
echo " .. Calculated answer = $calc\n";
echo " .. Expected answer = $answer\n\n";
}
die("end of test");
// ********** conversion function *******
function ieeeConvert($hex, $places = 4) {
if (!ereg('^[0-9A-F]{8}$',$hex) ) {
echo "Input must be 8 hex digits - $hex is invalid\n";
return 0.0;
}
if ($hex == '00000000') $val = 0.0;
else {
$binary = str_pad( base_convert($hex, 16, 2),
32, "0", STR_PAD_LEFT);
$sign = ($binary[0] == '0' ? 1 : -1);
$exp = substr($binary, 1, 8);
$exp = base_convert($exp,2,10) - 127;
$exp = pow(2,$exp);
$mantissa = substr($binary,9);
$mantissa = 1.0 +
(base_convert($mantissa,2,10) / 8388608.0);
$val = round($sign * $exp * $mantissa, $places);
}
return $val;
}
?>