1

You can read a binary file byte by byte using f:read(size) in which size represent the number of byte but how can I read it bit by bit ? (1/8 of byte or octet if you want)

It's ok for most of the data Int8(1),Uint16(2),Uint32(4),Int*(4) But for BOOL(0.125 ?).

Thanks for your help !

EDIT : My problem is obviously not to read the file bit by bit but to manage to extract all the data, including some boolean value (without creating a "shift" of 1 bit).

4nti7rust
  • 116
  • 10
  • Just read bytes and parse bits from them. If you provide more details on structure of your data, people can give more detailed answers. – Oleg V. Volkov Sep 06 '12 at 09:29

1 Answers1

1

You can't. A byte is the smallest unit that can be read from a file. You could write code that wraps the bytewise access to make it look bitwise.

The appropriate way to read a boolean value from a file depends on how it was written. Unless you go to the exact same sort of trouble to write boolean values bit by bit then there's no need to read them that way.

The Lua file API only deals in numbers and strings. To write a boolean value you'd convert it to one of these types. To read it you would read one of these types and the perform the inverse of the conversion you used for writing. For example you might convert true to 1 and false to 0, and then write and read numbers. Or you might try to pack several boolean values into one number. In any case, you don't need to read or write the file bit by bit to read and write boolean data.

bames53
  • 86,085
  • 15
  • 179
  • 244
  • If you want to be technical, you can't read bytes from files either. You read them page by page, and buffer pages when you only wanted a byte from them. – Nicol Bolas Sep 05 '12 at 17:10
  • 3
    @NicolBolas: That is not true, since the kernel provides `read` and `write` functions with 1-byte resolution, and maintains the file's size, again in bytes. – finnw Sep 05 '12 at 19:51
  • " You could write code that wraps the bytewise access to make it look bitwise."                                         That's exactly what I'm looking for. Can you help me with that ? – 4nti7rust Sep 06 '12 at 07:29
  • If I understand, I will need to read a certain number of byte and then split it into my different types of value, but I could not manage to find a function to read only a bit ... – 4nti7rust Sep 06 '12 at 07:38
  • I think I can do something using modulo etc. But I hope there is an easier way ... – 4nti7rust Sep 06 '12 at 08:47
  • Finally I found another version of the binary file I was trying to read in which Bool are written in 1 byte. So it's ok but thanks a lot for your help !! (Should I do something else than just clicking the accept answer button ?) – 4nti7rust Sep 06 '12 at 12:18