2

How can I convert from bytes to float in php? Like in Java

int i = (byte3 & 0xff) << 24 | (byte2 & 0xff) << 16 | (byte1 & 0xff) << 8 | byte0 & 0xff; 
Float.intBitsToFloat(i);
mskfisher
  • 3,291
  • 4
  • 35
  • 48
Valdas
  • 109
  • 1
  • 2
  • 4

3 Answers3

5

There may be a more direct way, but here you go:

<?php
var_dump(unpack('f', pack('i', 1059760811)));
?>

This is, of course, machine dependent, but I don't know of any machine running PHP that doesn't use IEEE 754 floats.

Matthew
  • 47,584
  • 11
  • 86
  • 98
0

I don't think php has bytes, does it? When you assign a number to a variable you'll get an variable with a number type

$a = 10; // integer
$f = 1.0; // double
$b = $a + $f; // $b is double
Mene
  • 3,739
  • 21
  • 40
  • yes php not have bytes system. but i have to make from bytes to float. it's bytes: 1059760811 > 0.6666667 (float) – Valdas Apr 12 '10 at 19:51
  • out of interest, which programming language does have the *byte* variable type? – Mathew Apr 12 '10 at 19:52
  • I have remade one script form java to php. it will be last task. In java it easy: Float.intBitsToFloat(integer); – Valdas Apr 12 '10 at 19:57
  • 1
    @MatW: Strangely enough, Java and C# have a byte variable type... but it's just a 1 byte unsigned number type (values 0-255). – Powerlord Apr 12 '10 at 19:59
  • Valdas, that's an integet to a float. I don't get how you get 2/3rd from that integer though.. – Arda Xi Apr 12 '10 at 20:00
  • Incidentally, Float.intBitsToFloat is described here: http://java.sun.com/javase/6/docs/api/java/lang/Float.html#intBitsToFloat%28int%29 – Powerlord Apr 12 '10 at 20:00
  • I dont know in JAVA i checked. In php manual: For instance, 1/3 in decimal form becomes 0.3. – Valdas Apr 12 '10 at 20:02
  • @OMG Unicorns Thx +1. If I could give you extra for the username, I would! – Mathew Apr 12 '10 at 20:03
  • @MatW: Ha, I changed it for April Fools Day, but can't change it back until May 1st. :D – Powerlord Apr 12 '10 at 20:17
  • Ah, now I understand what you are trying to do ^^ – Mene Apr 13 '10 at 11:10
0

If I'm understanding you correctly, you want to take a raw 32- or 64-bit "integer" value, and force that set of bits to treated as a floating point number instead?

Try the 'pack' and 'unpack' functions

Marc B
  • 356,200
  • 43
  • 426
  • 500