|  | Home · Overviews · Examples |

# QBitArray Class Reference
[com.trolltech.qt.core module]

The `QBitArray` class provides an array of bits. More...

## Detailed Description

The `QBitArray` class provides an array of bits.

A `QBitArray` is an array that gives access to individual bits and provides operators (AND, OR, XOR, and NOT) that work on entire arrays of bits. It uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data.

The following code constructs a `QBitArray` containing 200 bits initialized to false (0):

        QBitArray ba(200);

To initialize the bits to true, either pass `true` as second argument to the constructor, or call `fill` later on.

`QBitArray` uses 0-based indexes, just like C++ arrays. To access the bit at a particular index position, you can use operator[](). On non-const bit arrays, operator[]() returns a reference to a bit that can be used on the left side of an assignment. For example:

        QBitArray ba;
        ba.resize(3);
        ba[0] = true;
        ba[1] = false;
        ba[2] = true;

For technical reasons, it is more efficient to use `testBit` and `setBit` to access bits in the array than operator[](). For example:

        QBitArray ba(3);
        ba.setBit(0, true);
        ba.setBit(1, false);
        ba.setBit(2, true);

`QBitArray` supports `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), as well as `&=`, `|=`, and `^=`. These operators work in the same way as the built-in C++ bitwise operators of the same name. For example:

        QBitArray x(5);
        x.setBit(3, true);
        // x: [ 0, 0, 0, 1, 0 ]

        QBitArray y(5);
        y.setBit(4, true);
        // y: [ 0, 0, 0, 0, 1 ]

        x |= y;
        // x: [ 0, 0, 0, 1, 1 ]

For historical reasons, `QBitArray` distinguishes between a null bit array and an empty bit array. A null bit array is a bit array that is initialized using `QBitArray`'s default constructor. An empty bit array is any bit array with size 0. A null bit array is always empty, but an empty bit array isn't necessarily null:

        QBitArray().isNull();           // returns true
        QBitArray().isEmpty();          // returns true

        QBitArray(0).isNull();          // returns false
        QBitArray(0).isEmpty();         // returns true

        QBitArray(3).isNull();          // returns false
        QBitArray(3).isEmpty();         // returns false

All functions except `isNull` treat null bit arrays the same as empty bit arrays; for example, `QBitArray` compares equal to `QBitArray`(0). We recommend that you always use `isEmpty` and avoid `isNull`.

See also `QByteArray` and `QVector`.