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
You'll get bytes. PHP strings are single-byte.
Convert a character to a number with
ord
, make your calculations and, if needed, convert back withchr
. Alternatively, convert the whole buffer withunpack('c*', $buf)
, which gives you a numeric array.