30 thg 10, 2010

Representing Arrays as Streams of Bits

NGUON: http://www.codeguru.com/cpp/cpp/cpp_mfc/bits/article.php/c4087/Representing-Arrays-as-Streams-of-Bits.htm

  • 1
Environment: MFC
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:
  1. Declare a CByteArray object.
  2. Declare a CBitStream object, supplying a reference to the newly created CByteArray object to the constructor of the first one.
  3. Enjoy. :)
To set/get the next bit, you can use either overloaded shifting operators or SetBit()/GetBit() functions. Also, you can navigate inside the array of data. You can set a "pointer" to any bit inside your array.
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.

Downloads

Download demo project - 10 Kb
Download source - 3 Kb

Không có nhận xét nào:

Đăng nhận xét