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);
5
  • Can you give an example of how you expect that bytes are converted to float? Commented Apr 12, 2010 at 19:43
  • do you mean convert int to float? Commented Apr 12, 2010 at 19:46
  • Example: it's bytes: 1059760811 Must be in float 0.6666667 Commented Apr 12, 2010 at 19:52
  • 1059760811 is not by any definition a byte number. Bytes range from 0-255. Commented Apr 12, 2010 at 19:55
  • How can i remade: int i = (byte3 & 0xff) << 24 | (byte2 & 0xff) << 16 | (byte1 & 0xff) << 8 | byte0 & 0xff; Float.intBitsToFloat(i); Commented Apr 12, 2010 at 19:59

3 Answers 3

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.

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

Comments

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

10 Comments

yes php not have bytes system. but i have to make from bytes to float. it's bytes: 1059760811 > 0.6666667 (float)
out of interest, which programming language does have the byte variable type?
I have remade one script form java to php. it will be last task. In java it easy: Float.intBitsToFloat(integer);
@MatW: Strangely enough, Java and C# have a byte variable type... but it's just a 1 byte unsigned number type (values 0-255).
Valdas, that's an integet to a float. I don't get how you get 2/3rd from that integer though..
|
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

Comments

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.