Logo Search packages:      
Sourcecode: qt4-x11 version File versions  Download package

QByteArray Class Reference

Inheritance diagram for QByteArray:


List of all members.

Detailed Description

The QByteArray class provides an array of bytes.

QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings. Using QByteArray is much more convenient than using {const char *}. Behind the scenes, it always ensures that the data is followed by a '\0' terminator, and uses {implicit sharing} (copy-on-write) to reduce memory usage and avoid needless copying of data.

In addition to QByteArray, Qt also provides the QString class to store string data. For most purposes, QString is the class you want to use. It stores 16-bit Unicode characters, making it easy to store non-ASCII/non-Latin-1 characters in your application. Furthermore, QString is used throughout in the Qt API. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g. with Qtopia Core).

One way to initialize a QByteArray is simply to pass a {const char *} to its constructor. For example, the following code creates a byte array of size 5 containing the data "Hello":

        QByteArray ba("Hello");

Although the size() is 5, the byte array also maintains an extra '\0' character at the end so that if a function is used that asks for a pointer to the underlying data (e.g. a call to data()), the data pointed to is guaranteed to be '\0'-terminated.

QByteArray makes a deep copy of the {const char *} data, so you can modify it later without experiencing side effects. (If for performance reasons you don't want to take a deep copy of the character data, use QByteArray::fromRawData() instead.)

Another approach is to set the size of the array using resize() and to initialize the data byte per byte. QByteArray uses 0-based indexes, just like C++ arrays. To access the byte at a particular index position, you can use operator[](). On non-const byte arrays, operator[]() returns a reference to a byte that can be used on the left side of an assignment. For example:

        QByteArray ba;
        ba[0] = 0x3c;
        ba[1] = 0xb8;
        ba[2] = 0x64;
        ba[3] = 0x18;
        ba[4] = 0xca;

For read-only access, an alternative syntax is to use at():

        for (int i = 0; i < ba.size(); ++i) {
            if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
                cout << "Found character in range [a-f]" << endl;

at() can be faster than operator[](), because it never causes a {deep copy} to occur.

To extract many bytes at a time, use left(), right(), or mid().

A QByteArray can embed '\0' bytes. The size() function always returns the size of the whole array, including embedded '\0' bytes. If you want to obtain the length of the data up to and excluding the first '\0' character, call qstrlen() on the byte array.

After a call to resize(), newly allocated bytes have undefined values. To set all the bytes to a particular value, call fill().

To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the data. The pointer is guaranteed to remain valid until a non-const function is called on the QByteArray. It is also guaranteed that the data ends with a '\0' byte. This '\0' byte is automatically provided by QByteArray and is not counted in size().

QByteArray provides the following basic functions for modifying the byte data: append(), prepend(), insert(), replace(), and remove(). For example:

        QByteArray x("and");
        x.prepend("rock ");         // x == "rock and"
        x.append(" roll");          // x == "rock and roll"
        x.replace(5, 3, "&");       // x == "rock & roll"

The replace() and remove() functions' first two arguments are the position from which to start erasing and the number of bytes that should be erased.

When you append() data to a non-empty array, the array will be reallocated and the new data copied to it. You can avoid this behavior by calling reserve(), which preallocates a certain amount of memory. You can also call capacity() to find out how much memory QByteArray actually allocated. Data appended to an empty array is not copied.

A frequent requirement is to remove whitespace characters from a byte array ('\n', '\t', ' ', etc.). If you want to remove whitespace from both ends of a QByteArray, use trimmed(). If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the byte array, use simplified().

If you want to find all occurrences of a particular character or substring in a QByteArray, use indexOf() or lastIndexOf(). The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here's a typical loop that finds all occurrences of a particular substring:

        QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
        int j = 0;
        while ((j = ba.indexOf("<b>", j)) != -1) {
            cout << "Found <b> tag at index position " << j << endl;

If you simply want to check whether a QByteArray contains a particular character or substring, use contains(). If you want to find out how many times a particular character or substring occurs in the byte array, use count(). If you want to replace all occurrences of a particular value with another, use one of the two-parameter replace() overloads.

QByteArrays can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. The comparison is based exclusively on the numeric values of the characters and is very fast, but is not what a human would expect. QString::localeAwareCompare() is a better choice for sorting user-interface strings.

For historical reasons, QByteArray distinguishes between a null byte array and an empty byte array. A null byte array is a byte array that is initialized using QByteArray's default constructor or by passing (const char *)0 to the constructor. An empty byte array is any byte array with size 0. A null byte array is always empty, but an empty byte array isn't necessarily null:

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

        QByteArray("").isNull();        // returns false
        QByteArray("").isEmpty();       // returns true

        QByteArray("abc").isNull();     // returns false
        QByteArray("abc").isEmpty();    // returns false

All functions except isNull() treat null byte arrays the same as empty byte arrays. For example, data() returns a pointer to a '\0' character for a null byte array (not a null pointer), and QByteArray() compares equal to QByteArray(""). We recommend that you always use isEmpty() and avoid isNull().

Definition at line 119 of file qbytearray.h.

Public Types

typedef const char * const_iterator
typedef const char & const_reference
typedef const_iterator ConstIterator
typedef Data * DataPtr
typedef iterator Iterator
typedef char * iterator
typedef char & reference

Public Member Functions

QT_ASCII_CAST_WARN QByteArrayappend (const QString &s)
QByteArrayappend (const QByteArray &a)
QByteArrayappend (const char *s)
QByteArrayappend (char c)
const char at (int i) const
const_iterator begin () const
iterator begin ()
int capacity () const
void chop (int n)
void clear ()
const_iterator constBegin () const
const char * constData () const
const_iterator constEnd () const
QBool contains (const QByteArray &a) const
QBool contains (const char *a) const
QBool contains (char c) const
int count () const
int count (const QByteArray &a) const
int count (const char *a) const
int count (char c) const
const char * data () const
char * data ()
DataPtrdata_ptr ()
void detach ()
const_iterator end () const
iterator end ()
bool endsWith (const char *c) const
bool endsWith (char c) const
bool endsWith (const QByteArray &a) const
QByteArrayfill (char c, int size=-1)
QT_ASCII_CAST_WARN int indexOf (const QString &s, int from=0) const
int indexOf (const QByteArray &a, int from=0) const
int indexOf (const char *c, int from=0) const
int indexOf (char c, int from=0) const
QT_ASCII_CAST_WARN QByteArrayinsert (int i, const QString &s)
QByteArrayinsert (int i, const QByteArray &a)
QByteArrayinsert (int i, const char *s)
QByteArrayinsert (int i, char c)
bool isDetached () const
bool isEmpty () const
bool isNull () const
QT_ASCII_CAST_WARN int lastIndexOf (const QString &s, int from=-1) const
int lastIndexOf (const QByteArray &a, int from=-1) const
int lastIndexOf (const char *c, int from=-1) const
int lastIndexOf (char c, int from=-1) const
QByteArray left (int len) const
QByteArray leftJustified (int width, char fill= ' ', bool truncate=false) const
int length () const
QByteArray mid (int index, int len=-1) const
 operator const char * () const
 operator const void * () const
QT_ASCII_CAST_WARN bool operator!= (const QString &s2) const
QT_ASCII_CAST_WARN QByteArrayoperator+= (const QString &s)
QByteArrayoperator+= (const QByteArray &a)
QByteArrayoperator+= (const char *s)
QByteArrayoperator+= (char c)
QT_ASCII_CAST_WARN bool operator< (const QString &s2) const
QT_ASCII_CAST_WARN bool operator<= (const QString &s2) const
QByteArrayoperator= (const char *str)
QByteArrayoperator= (const QByteArray &)
QT_ASCII_CAST_WARN bool operator== (const QString &s2) const
QT_ASCII_CAST_WARN bool operator> (const QString &s2) const
QT_ASCII_CAST_WARN bool operator>= (const QString &s2) const
QByteRef operator[] (uint i)
const char operator[] (uint i) const
QByteRef operator[] (int i)
const char operator[] (int i) const
QByteArrayprepend (const QByteArray &a)
QByteArrayprepend (const char *s)
QByteArrayprepend (char c)
void push_back (const QByteArray &a)
void push_back (const char *c)
void push_back (char c)
void push_front (const QByteArray &a)
void push_front (const char *c)
void push_front (char c)
 QByteArray (const QByteArray &)
 QByteArray (int size, char c)
 QByteArray (const char *, int size)
 QByteArray (const char *)
 QByteArray ()
QByteArrayremove (int index, int len)
QT_ASCII_CAST_WARN QByteArrayreplace (const QString &before, const QByteArray &after)
QT_ASCII_CAST_WARN QByteArrayreplace (char c, const QString &after)
QT_ASCII_CAST_WARN QByteArrayreplace (const QString &before, const char *after)
QByteArrayreplace (char before, char after)
QByteArrayreplace (const char *before, const QByteArray &after)
QByteArrayreplace (const QByteArray &before, const char *after)
QByteArrayreplace (const QByteArray &before, const QByteArray &after)
QByteArrayreplace (const char *before, const char *after)
QByteArrayreplace (char before, const QByteArray &after)
QByteArrayreplace (char before, const char *after)
QByteArrayreplace (int index, int len, const QByteArray &s)
QByteArrayreplace (int index, int len, const char *s)
void reserve (int size)
void resize (int size)
QByteArray right (int len) const
QByteArray rightJustified (int width, char fill= ' ', bool truncate=false) const
QByteArraysetNum (double, char f= 'g', int prec=6)
QByteArraysetNum (float, char f= 'g', int prec=6)
QByteArraysetNum (qulonglong, int base=10)
QByteArraysetNum (qlonglong, int base=10)
QByteArraysetNum (uint, int base=10)
QByteArraysetNum (int, int base=10)
QByteArraysetNum (ushort, int base=10)
QByteArraysetNum (short, int base=10)
QByteArray simplified () const
int size () const
QList< QByteArraysplit (char sep) const
void squeeze ()
bool startsWith (const char *c) const
bool startsWith (char c) const
bool startsWith (const QByteArray &a) const
QByteArray toBase64 () const
double toDouble (bool *ok=0) const
float toFloat (bool *ok=0) const
QByteArray toHex () const
int toInt (bool *ok=0, int base=10) const
long toLong (bool *ok=0, int base=10) const
qlonglong toLongLong (bool *ok=0, int base=10) const
QByteArray toLower () const
short toShort (bool *ok=0, int base=10) const
uint toUInt (bool *ok=0, int base=10) const
ulong toULong (bool *ok=0, int base=10) const
qulonglong toULongLong (bool *ok=0, int base=10) const
QByteArray toUpper () const
ushort toUShort (bool *ok=0, int base=10) const
QByteArray trimmed () const
void truncate (int pos)
 ~QByteArray ()

Static Public Member Functions

static QByteArray fromBase64 (const QByteArray &base64)
static QByteArray fromHex (const QByteArray &hexEncoded)
static QByteArray fromRawData (const char *, int size)
static QByteArray number (double, char f= 'g', int prec=6)
static QByteArray number (qulonglong, int base=10)
static QByteArray number (qlonglong, int base=10)
static QByteArray number (uint, int base=10)
static QByteArray number (int, int base=10)

Private Member Functions

void expand (int i)
 operator QNoImplicitBoolCast () const
 QByteArray (Data *dd, int, int)
void realloc (int alloc)

Private Attributes

Data * d

Static Private Attributes

static Data shared_empty = { Q_ATOMIC_INIT(1), 0, 0, shared_empty.array, {0} }
static Data shared_null = {Q_ATOMIC_INIT(1), 0, 0, shared_null.array, {0} }


class QByteRef
class QString

Related Functions

(Note that these are not member functions.)

bool operator!= (const char *a1, const QByteArray &a2)
bool operator!= (const QByteArray &a1, const char *a2)
bool operator!= (const QByteArray &a1, const QByteArray &a2)
const QByteArray operator+ (char a1, const QByteArray &a2)
const QByteArray operator+ (const char *a1, const QByteArray &a2)
const QByteArray operator+ (const QByteArray &a1, char a2)
const QByteArray operator+ (const QByteArray &a1, const char *a2)
const QByteArray operator+ (const QByteArray &a1, const QByteArray &a2)
bool operator< (const char *a1, const QByteArray &a2)
bool operator< (const QByteArray &a1, const char *a2)
bool operator< (const QByteArray &a1, const QByteArray &a2)
QDataStreamoperator<< (QDataStream &out, const QByteArray &ba)
bool operator<= (const char *a1, const QByteArray &a2)
bool operator<= (const QByteArray &a1, const char *a2)
bool operator<= (const QByteArray &a1, const QByteArray &a2)
bool operator== (const char *a1, const QByteArray &a2)
bool operator== (const QByteArray &a1, const char *a2)
bool operator== (const QByteArray &a1, const QByteArray &a2)
bool operator> (const char *a1, const QByteArray &a2)
bool operator> (const QByteArray &a1, const char *a2)
bool operator> (const QByteArray &a1, const QByteArray &a2)
bool operator>= (const char *a1, const QByteArray &a2)
bool operator>= (const QByteArray &a1, const char *a2)
bool operator>= (const QByteArray &a1, const QByteArray &a2)
QDataStreamoperator>> (QDataStream &in, QByteArray &ba)
quint16 qChecksum (const char *data, uint len)
QByteArray qCompress (const uchar *data, int nbytes, int compressionLevel)
QByteArray qCompress (const QByteArray &data, int compressionLevel)
int qsnprintf (char *str, size_t n, const char *fmt,...)
int qstrcmp (const char *str1, const char *str2)
char * qstrcpy (char *dst, const char *src)
char * qstrdup (const char *src)
int qstricmp (const char *str1, const char *str2)
uint qstrlen (const char *str)
int qstrncmp (const char *str1, const char *str2, uint len)
char * qstrncpy (char *dst, const char *src, uint len)
int qstrnicmp (const char *str1, const char *str2, uint len)
uint qstrnlen (const char *str, uint maxlen)
QByteArray qUncompress (const uchar *data, int nbytes)
QByteArray qUncompress (const QByteArray &data)
int qvsnprintf (char *str, size_t n, const char *fmt, va_list ap)


struct  Data

The documentation for this class was generated from the following files:

Generated by  Doxygen 1.6.0   Back to index