PHP 字符串的字节运算和操作

Byte arithmetic and manipulation of PHP string

如果我使用 $data = fread('myfile','rb') 将二进制文件读入变量,我如何才能一次处理 $data 个字节。我还想对每个字节进行运算,比如乘以一个数,然后对另一个数求模。

我可以使用 $data[$i] 将变量作为数组引用,但是我得到的字节是这个字符还是可能是多字节字符?此外,当我这样做时,我无法对结果进行计算,例如 $data[$i]*4,它始终为零。

我需要处理非常大的文件,因此解决方案需要快速。

谢谢

I can reference the variable as an array using $data[$i], but am I getting bytes with this or possibly multi-byte characters?

您将获得字节。 PHP 字符串是单字节的。

Also when I do this, I can't then perform calculations on the results, such as $data[$i]*4, which is always zero.

使用 ord 将字符转换为数字,进行计算,如果需要,使用 chr 转换回数字。或者,使用 unpack('c*', $buf) 转换整个缓冲区,这会为您提供一个数字数组。