0

I get through Modbus some 4-Byte Float Values. I get this 4 bytes in an array: Array ( [0] => 67 [1] => 105 [2] => 25 [3] => 154 ) After some Bitconversion I made this: 1000011011010010001100110011010

when putting this binary string into a online converter such as https://www.binaryconvert.com/result_float.html?hexadecimal=4369199A I get the value of 2.331E2 which is correct (233.1).

However I fail to convert this binary in a PHP float variable. I tried to point the address to a float variable, but did not succeed.

How can I convert this binary string or the array above into a php float?

Added: The pointer Idea was stupid, since php does not let me define the type of variable. So I tried a different approach using unpack to a float type. But it does not work either:

// This represents a 4 byte float read from modbus
$array=array(67,105,25,154);
$array=array_reverse($array);
print_r($array);
for ($i=0;$i<count($array);$i++) {
    $t+=pow(2,$i*8)*$array[$i];
}
echo '<br>Binary: '.decbin($t). ' - This would be the correct Binary for 233.1';
echo '<br>float: ';
print_r(unpack('f',$t));

This code results in:

Array ( [0] => 154 [1] => 25 [2] => 105 [3] => 67 )
Binary: 1000011011010010001100110011010 - This would be the correct Binary for 233.1
float: Array ( [1] => 6.5189725839687E-10 )

No chance to get my 233.1 :(

Wolfgang
  • 81
  • 8

1 Answers1

1

I know I come with a possible answer a little bit later but maybe others found useful. The conversion is a little bit complicated, I worked few hours on it to include in my application.

Firstly I created a function to get value of the Mantissa, then calculated a float number. I didn't created function for the calculation of the exponent and sign.

This example is valid for positive float numbers, for more details read this:

HOW REAL (FLOATING POINT) AND 32-BIT DATA IS ENCODED IN MODBUS RTU MESSAGES

And the script:

$array=array(67,105,25,154);
$result = pow(2,(((($array[0] * 256 + $array[1]) & 32640) >> 7)-127)) * calcMantissa((($array[1] & 127) << 16) + ($array[2] << 8) + $array[3]+1);
echo $result . "\n";

function calcMantissa($nb) {
    $retValue = 1;
    for ($i = 0; $i < 22; $i++) {
        $retValue = $retValue + (($nb & (1 << (22 - $i))) > 0) / (pow(2,($i+1))) ;
    }
    return $retValue;
}

which gave the following result:

233.10000610352
jv-k
  • 618
  • 5
  • 20
Zsugo
  • 23
  • 6