Skip to content

Instantly share code, notes, and snippets.

@mrios
Last active March 22, 2016 16:05
Show Gist options
  • Save mrios/8bcfcc6aada09e083085 to your computer and use it in GitHub Desktop.
Save mrios/8bcfcc6aada09e083085 to your computer and use it in GitHub Desktop.
Single-precision floating-point format is a computer number format that occupies 4 bytes (32 bits) in computer memory and represents a wide dynamic range of values by using a floating point.
<?php
/***
* Create a PHP function that takes an array of 32 boolean values
* (zeroes and ones) as parameter, and answers with a numeric value.
* The result value must be calculated by processing the array
* parameter, which symbolizes an IEE-754 compliant Floating Point
* Single Precision 32bit value.
*
* More docs @wikipedia: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
*/
function compute($input) {
#Checking length input
if(count($input)==32) {
#Getting reverse input to respect original equations
$b = array_reverse($input);
#Factor 1
$factor1 = pow(-1,$b[31]);
#Factor 2
$significant_precision = 0;
for($i=1;$i<24;$i++){
$significant_precision += $b[23-$i]*pow(2,-$i);
}
$factor2 = 1 + $significant_precision;
#Factor 3
$exponent = 0;
for($i=0;$i<7;$i++){
$exponent += $b[23+$i]*pow(2,$i);
}
$factor3 = pow(2,($exponent-127));
$result = $factor1*$factor2*$factor3;
echo "Value = $factor1 x $factor2 x $factor3 = $result";
return $result;
}
else
echo "Wrong input, must to be 32 bits length!";
}
#Example from docs
$input = [0,0,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
$result = compute($input);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment