How do I read and write a stream 3 bits at a time?

209 Views Asked by At

I'm trying to make an ultra-compressed variant of brainfuck, which is an esoteric programming language with 8 instructions. Since 3 bits is the minimum amount of storage to store 8 values, I went with that. The part I'm stuck on is how to read a number of bits that isn't a power of 2.

I tried using std::bitset, but that just serializes to a string that is 1 byte per bit, which is the opposite of what I want. How would I go about this?

2

There are 2 best solutions below

0
Erlkoenig On BEST ANSWER

Read 3 bytes at a time, and split those into 8 packs of 3 bits each using the >> and & operators. Put these in an ordinary uint8_t array to simplify later access and jumps.

0
Lightness Races in Orbit On

You don't read bits from a stream, you read bytes from a stream.

So, you must do so, then shuffle the component bits around as you wish using bitwise arithmetic.

By the way, the fact that computers work in bytes also means that many of your programs (any that don't have a multiple of 8 instructions) are necessarily going to have wasted space.