I wrote this class when I needed to extract separate bits of data from an array, one by one. After some calculations, I found I needed to put modified bits in another array of data. I think this class may be useful, so here it is.
This class operates with data located in the CByteArray object. So, the common steps to use CBitStream are:
- Declare a CByteArray object.
- Declare a CBitStream object, supplying a reference to the newly created CByteArray object to the constructor of the first one.
- Enjoy. :)
Also, you can choose the order in which bits of every byte will be processed. The default is a "left-to-right" order. In this order, the bits affected are: 7th, 6th, 5th, 4th, 3rd, 2nd, 1st, and then the 0 bit. You can define the RIGHTTOLEFTFILL identifier to change the order to right-to-left, in which bits are accessed: 0, 1st, 2nd, 3rd, 4th, 5th, 6th, and then 7th. I prefer the left-to-right order because it is easier to understand. Look to the picture below. a) is the left-to-right order (default) and b) is the right-to-left order.
CByteArray array; CBitStream stream(array); stream<<0<<1<<0<<0<<1<<0<<0<<1; // The first byte now consists of 01001001 bits, so it equals 73 // (0x49). It's true when you are using the left-to-right order. stream.SetBit(0); stream.SetBit(1); stream.SetBit(0); stream.SetBit(0); stream.SetBit(1); stream.SetBit(0); stream.SetBit(0); stream.SetBit(1); // The second byte is now the same as the first.
DownloadsDownload demo project - 10 Kb
Download source - 3 Kb