The effective choice will depend on where your bottleneck is. Since you are specifically asking about inserts, I assume that your application needs to do a lot of random access inserts, and in fact you only need to read the full stream from time to time in order. If this is the case, here are a few options:
Option 1: Linked Byte List
struct BitStreamNode; { Byte size; Byte bits; BitStreamNode * next; };
This will work best in cases where you can maintain a pointer to the node into which you want to insert the bit. If you need to specify the insertion point as a numeric index, see Option 2. Note that I have included the size element. This will allow you to insert two bits as follows:
BitStreamNode newNode; newNode.bits = 0x02; // for example newNode.size = 2; newNode.next = nodeToInsertAfter.next; nodeToInsertAfter.next = newNode;
Inserting in the middle of an existing node, of course, will require splitting the node into two parts. Again, let me emphasize that this will only be more efficient than shuffling the entire array to the right if you a) do it quite often and b) get a large number of bits in your stream.
Option 2: Balanced Tree Structure
This method will use a similar node, as indicated in option 1, but will include a numerical index in each node and a link to nodes with a higher and lower index. The main idea is a binary search tree tree , which reduces the time required to find the exact location of a particular node in the stream, but with the addition of links in order to the next and previous nodes (in order to be able to read the stream in order).
Update: The exact definition looks like a threaded tree . "
This will require a lot of work on the correct implementation, so I would recommend to go only along this route, if you are absolutely sure that the increase in speed will be worth it. that is, the profile of the main brute force decision, and then evaluate the pros and cons to make additional efforts and complexity.