1

I need to convert a float value into 4 bytes.

In javascript I usually do it with this code:

  var farr = new Float32Array(1);
  farr[0] = 26.75;
  var barr = new Int8Array(farr.buffer);
  console.log(barr[0]+","+barr[1]+","+barr[2]+","+barr[3]); 
  //26.75 => 0,0,-42,65
  //26.85 => -51,-52,-42,65

I want to do it in php instead of javascript. I it possible?

1

1 Answer 1

3

try to use pack and unpack function:

$f = 26.75;
$ar = unpack("c*", pack("f", $f));

print_r($ar);

Result:

Array
(
  [1] => 0
  [2] => 0
  [3] => -42
  [4] => 65
)

you can find a snippet here

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but I don't get the same values with this code as I got with javascript. It you try my 2 examples, values now are differents: 26.85 gives 205 204 222 65
@Biribu 205 - 256 = 51, same for other numbers, you should subtract the numbers by 256 if they are larger then 128 to compensate for php not giving the number signed (or javascript giving the number unsigned)
Perfect. Thanks both.
@Biribu, just use signed char 'c': unpack("c*", pack("f", $f));
For a ModBus float representation You have to use 'v*':unpack("v*", pack("f", $f)); This results in a two register little endianed uint16 "float"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.