Link to Bitset

From http://www.cplusplus.com/reference/stl/bitset/ :

Since such a small element type does not exist in most C ++ environments, individual elements are referred to as special links that mimic elements bool.

How does this bit work work?

The only way I could think of is to use the static array chars, but then each instance will need to store its index in the array. Because each reference instance would have at least size a size_t, which would destroy the compactness of the bit set. In addition, resizing can be slow, and bit manipulation is expected quickly.

+5
source share
4 answers

I think you are mixing two things.

A class bitsetstores bits in compact representations, for example. in an array char, usually 8 bits per char(but YMMV on "exotic" platforms).

A class is bitset::referenceprovided to allow class users to bitsethave reference objects to bits stored in bitset.

, , bitset ( char), lvalue . , , , , operator[], "" lvalue (, , 99% "" ). "-".

-to- bool; bitset::reference, , bitset ( + ) , , .

--- EDIT ---

, g++ bitset::reference , , . , , , .

, , , bitset::reference :
  /**
   *  This encapsulates the concept of a single bit.  An instance of this
   *  class is a proxy for an actual bit; this way the individual bit
   *  operations are done as faster word-size bitwise instructions.
   *
   *  Most users will never need to use this class directly; conversions
   *  to and from bool are automatic and should be transparent.  Overloaded
   *  operators help to preserve the illusion.
   *
   *  (On a typical system, this <em>bit %reference</em> is 64
   *  times the size of an actual bit.  Ha.)
   */
+5

STL, , Bitset size size_t. .

, ( ), . char. A char 8 , char , 32 64 .

+1

, , , , , , . . . . .

0

, , , , , , , . , Microsoft (!).

:

struct Byte
{
    bool bit1:1;
    bool bit2:1;
    bool bit3:1;
    bool bit4:1;
    bool bit5:1;
    bool bit6:1;
    bool bit7:1;
    bool bit8:1;
}

': 1' . http://msdn.microsoft.com/en-us/library/ewwyfdbe(v=vs.80).aspx , , 8 bools, 1 . "Byte" 1 .

, , char, Byte :

char a = 'a';
Byte oneByte;
oneByte = *(Byte*)(&a);   // Get the address of a (a pointer, basically), cast this  
                          // char* pointer to a Byte*,
                          // then use the reference operator to store the data that 
                          // this points to in the variable oneByte.

Now you can access (and change) individual bits by accessing the bool oneByte member variables. To save the changed data in char again, you can do the following:

char b;
b = *(char*)(&oneByte);   // Basically, this is the reverse of what you do to 
                          // store the char in a Byte.

I will try to find the source of this technique in order to give credit when there should be a loan.

Also, I'm not quite sure if this answer is right for you. I interpreted your question as "how would I access individual bits within myself?"

0
source

All Articles