1

我有由几个(+10k)个记录组成的二进制文件,每个记录有 6 个字节:

例如记录一个有这样的字节字符串ÿvDV

Ascii : 152 + 118 + 68 + 86 + 27 + 15
Binary: 000100000101101100000010010100110000000000000000

从字符串中,我必须在某个特定位置提取“一些”位的列表,然后将它们的值转换为整数:

1001100001110110 0100010001010110 0001101100001111
--     |-------| --     |-------| |------||------|
|          |      |          |        |       |
|          |      |          |        |       +------> 0001111     => $bin  = 1 5
|          |      |          |        +--------------> 00011011    => $site = 27
|          |      |          +-----------------------> 001010110   => $x    = 86
|          |      +----------------------------------> 01          => $dp   = 1
|          +-----------------------------------------> 001110110   => $y    = 118
+----------------------------------------------------> 10          => $tr   = 2

有比这个更快的方法吗?

$binary = file_get_contents("/path/to/binary/file.dat");
$startbyte = 0; //I'm reading 55nth byte
while($startbyte <= strlen($binary)) {
    $record = unpack("n3", substr($binary, $startbyte, 6));
    $info = array(
        'tr'                => ($record[1] & 0xC000) >> 14,
        'y'                 => ($record[1] & 0x01FF),
        'dp'                => ($record[2] & 0xC000) >> 14,
        'x'                 => ($record[2] & 0x01FF),
        'site'              => (int) (($record[3] & 0x3F00) >> 8),
        'bin'               => (int) ($record[3] & 0x003F) + 1)
    );
    $startbyte += 6;
}

根据您的经验,会有更快的方法吗?

4

0 回答 0