Reading bit-aligned data

Viewed 1408

I have been reading the SWF format available on Adobe's site and it mentions that in order to save space, variable bits are used to store integers or floats (page 17 in the pdf)

I have always worked with byte-aligned data so have not given much thought to files that are bit-aligned, or have variable alignment where the information is stored in each byte.

So for example, you may have a struct containing four 13-bit integers stored sequentially ( rather than storing them as four 16-bit integers).

The first 13bits is the first integer, the next 13 bits is the second integer, and so on. It pads the last byte appropriate to make the struct byte-aligned with the rest of the file, so 52-bits would be padded to 56-bits, requiring 7 bytes to store those four integers as opposed to 8 bytes.

  • How do I approach this kind of problem?
  • How can I work with a stream of bytes at the bit-level?
  • Is there something I can use to help make it easier to work with this data?

I imagine the solution boils down to using bit-operations on byte arrays.

An example solution for parsing the four 13-bit integers would be nice as well to demonstrate the use of your suggested method.

2 Answers
Related