note 110107 deleted from function.fscanf by googleguy
| From: | googleguy@php.net | Date: | Thu, 20 Sep 2012 00:13:19 +0000 |
| Subject: | note 110107 deleted from function.fscanf by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190889@lists.php.net to get a copy of this message | ||
Note Submitter: i at blackrabbit dot info
----
I can't find out how to properly read an integer from a random place in a binary file, so I
wrote this function. It's a bicycle-style, and works only with unsigned, but it works for me:
function uintfread($fp, $intsize = 4, $endian = 'little')
{
if(!ftell($fp))
{
return false;
}
$result = 0;
$data = array();
for($i = 0; $i < $intsize; $i++)
{
$r = fread($fp, 1);
if($r == false)
{
$intsize = $i;
break;
}
$data[$i] = $r;
$data[$i] = ord($data[$i]);
}
if($endian == 'little')
{
$result = $data[$intsize-1];
if($intsize > 1)
{
for($i = $intsize-2; $i >= 0; $i--)
{
$result *= 256;
$result += $data[$i];
}
}
}
else
{
$result = $data[0];
if($intsize > 1)
{
for($i = 0; $i < $intsize; $i++)
{
$result *= 256;
$result += $data[$i];
}
}
}
return $result;
}