Reputation: 179
I have a very simple PHP code which should read a binary file, but it doesn't work:
<?php
$fid = fopen("sampleMdl.bin","rb");
echo "No. parts: " . fread($fid, 2) . "<br/>";
fclose($fid);
?>
The first 2 bytes of sampleMdl.bin contain the integer 2. But the page displays nothing after "No. parts:". Is there actually any setting in the server that avoids PHP to read binary file?
Upvotes: 0
Views: 283
Reputation: 179
Found the solution already by using a combination of unpack() and array_values():
<?php
$fid = fopen("sampleMdl.bin", "rb");
$NA = array_values(unpack("Sshort", fread(fid, 2)));
echo "No. parts: " . $NA[0] . "<br/>";
fclose($fid);
?>
Where the first 2 bytes of sampleMdl.bin is 02 00.
Upvotes: 0
Reputation: 109547
You read a binary integer.
$bytes = fread($fld, 2);
$n = $bytes[0] | ($bytes[1] << 8); // The number
This is a little endian format; it could also be the other way around, big endian:
$n = $bytes[1] | ($bytes[0] << 8); // The number
In this case negative numbers do not happen, so this suffices.
Upvotes: 1