从特定位置读取8个字节

时间:2018-03-07 08:16:14

标签: php

$filename = '301.tdr';

$packetStream = array(
    'buffer'    => '',
    'position'  => '',
    'size'      => ''
);

$packetStream['buffer'] = fopen($filename, 'rb');
$packetStream['position'] = 0;
$packetStream['size'] = filesize($filename);

while($packetStream['position'] < $packetStream['size']) {
    $groupID = decodeInt64($packetStream['buffer'], $packetStream['position']);
    echo $groupID;
    break;
}

function decodeInt64($stream, $position) {
    fseek($stream, $position);
    $packetStream['position'] += 8;
    return bindec(fgets($stream, 8));
}

您好,

我想在文件的特定位置读取8个字节。但我也希望二进制读取并获得二进制输出。因为,这个文件不是字符串等。它是一个二进制文件。

此代码对我不起作用,它返回0.但我预计5317 ..

1 个答案:

答案 0 :(得分:1)

除了您需要在$packetStream函数的开头声明globaldecodeInt64之外,如果您的文件包含字节并且您想显示其数值,那么需要使用fread阅读它们,然后获取ord。我将在此示例中返回一个数组。

function decodeInt64($stream, $position) {
    global $packetStream;
    fseek($stream, $position);
    $packetStream['position'] += 8;

    $bytes = fread($stream, 8);
    $toReturn = array();
    for($i = 0; $i < 8; $i++) {
        $toReturn[] = ord($bytes[$i]);
    }
    return $toReturn;
}