Byte arithmetic and manipulation of PHP string

224 views Asked by At

If I've read a binary file into a variable using $data = fread('myfile','rb') how can I work through $data a byte at a time. I also want to perform operations on each byte, such as multiplying it by a number and calculating the modulo with respect to another number.

I can reference the variable as an array using $data[$i], but am I getting bytes with this or possibly multi-byte characters? Also when I do this, I can't then perform calculations on the results, such as $data[$i]*4, which is always zero.

I need work through very large files so the solution needs to be quick.

Thanks

1

There are 1 answers

4
georg On BEST ANSWER

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

You'll get bytes. PHP strings are single-byte.

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

Convert a character to a number with ord, make your calculations and, if needed, convert back with chr. Alternatively, convert the whole buffer with unpack('c*', $buf), which gives you a numeric array.