lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 9/4/2010 9:15 PM, Patrick Mc(avery wrote:
I am having no trouble at all using Lua to manipulate bytes
according to PIL but on P198 it says

'you can even do pattern matching over binary data'

I would like to be able read and manipulate bits not bytes.

The code below manipulates a few "1"'s but should change thousands.


bin = io.open('29fb.bin', 'r') --29fb is 512 KB I am on Linux no "rb"
bin_all = bin:read("*all")
bin_zero, ntimes = bin_all.gsub(bin_all, '1', '0')

So bin_all should be a string 512KB in size. Check the #bin_all value.

Then you use string.byte to retrieve bytes, given the index (starting from 1).

On 5.2, you can use the bit library, else you cook up some functions to fiddle with byte values.

Of course, there are 101 ways to do it, you can convert to string '0's and '1's and fiddle with that; it depends on whether you are just prototyping, you need performance, etc.

Also see string.format for display purposes, since your processing and display may be two different things.

--
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia