24位整数在PHP中


24bit int in php

嘿,所以我遇到了一点问题,从PHP中,我必须从二进制文件中读取一些数据,其中SPACE至关重要,因此他们在某些地方使用了24位整数。

现在对于我可以使用解包读取的大部分数据,但是打包/解包不支持 24 位 int 的 :s

我想我也许可以简单地将数据(例如000104)读取为 H*,并将其读取到正确的变量中。

// example binary data say I had the following 3 bytes in a binary file
// 0x00, 0x01, 0x04
$buffer = unpack("H*", $data);
// this should equate to 260 in base 10 however unpacking as H* will not get
// this value.
// now we can't unpack as N as it requires 0x4 bytes of data and n being a 16 bit int
// is too short.

以前有人不得不处理这个问题吗?有什么解决办法吗?建议?

如果文件只有上述 3 个字节,最简单的方法是按照@DaveRandom所说的填充。但是,如果它是一个长文件,则此方法将变得效率低下。

在这种情况下,您可以将每个元素读取为 char 和 short,然后通过按位运算符重新打包它。

或者,您可以将 12 个字节读取为 3 个长,然后使用按位运算符将其分成 4 组,每组 3 个字节。剩余的字节将通过上述 2 种方法提取。这将是大数据上最快的解决方案。

unsigned int i, j;
unsigned int dataOut[SIZE];
for (i = 0, j = 0; j < size; i += 4, j += 3)
{
    dataOut[i]     = dataIn[j] >> 8;
    dataOut[i + 1] = ((dataIn[j] & 0xff) << 16) | (dataIn[j + 1] >> 16);
    dataOut[i + 2] = ((dataIn[j + 1] & 0xffff) << 8) | (dataIn[j + 2] >> 24);
    dataOut[i + 3] = dataIn[j + 2] & 0xffffff;
}

以下问题也有一个示例代码来解压缩 24/48 位的字符串