views:

22

answers:

1

Hello,

I have a 32-bit integer. The bit stream is actually a bit stream for a 32-bit float (IEEE 754). I tried converting it with:

unpack('f', $input);

This generates a float, but it seems it is not the right number

For example, if I pass in 1, I should be coming out with 1.4012984e-45, according to the IEEE754 converter, but I am coming with 2.5638762224389E-9

Thanks a lot for any help/advice.

A: 

You're confusing things:

<?php
$s = "\x01\x00\x00\x00";
$t = "0001"; //same as "\x30\x30\x30\x31"
var_dump(unpack('f', $s));
var_dump(unpack('f', $t));

gives

array(1) {
  [1]=>
  float(1.4012984643248E-45)
}
array(1) {
  [1]=>
  float(2.5638762224389E-9)
}

According to the manual, these results are not guaranteed (the "f" modifier in unpack will depend on the endianness of the system). But one thing is a byte stream which has actually those values and other thing is to have a byte stream which happens to translate to "0001" when the ASCII charset is considered.

Artefacto
I understand they are not the same. However, the $input that I pass in is not a string, but a number. Am I wrong in assuming that unpack('f', 1) and unpack('f', '\x01\x00\x00\x00') are equivalent? (on a little endian system, which is where this code will be run (x86/x64))
Goro
@Goro unpack expects a string, so it converts the number you pass it into a string. Type conversion rules in PHP make int(1) => string "1".
Artefacto
@Goro You can use a combination of pack and unpack. This will work regardless of the endianness of the system: `unpack('f', pack('L', 1)))`
Artefacto