QByteArray Class

The QByteArray class provides an array of bytes. More...

Header: #include <QByteArray>
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

class FromBase64Result
enum Base64Option { Base64Encoding, Base64UrlEncoding, KeepTrailingEquals, OmitTrailingEquals, IgnoreBase64DecodingErrors, AbortOnBase64DecodingErrors }
flags Base64Options
typedef const_iterator
typedef const_reverse_iterator
typedef iterator
typedef reverse_iterator

Public Functions

QByteArray(QByteArray &&other)
QByteArray(const QByteArray &other)
QByteArray(int size, char ch)
QByteArray(const char *data, int size = -1)
QByteArray()
QByteArray &operator=(QByteArray &&other)
QByteArray &operator=(const QByteArray &other)
~QByteArray()
QByteArray &append(const QByteArray &ba)
QByteArray &append(char ch)
QByteArray &append(int count, char ch)
QByteArray &append(const char *str)
QByteArray &append(const char *str, int len)
char at(int i) const
char back() const
QByteRef back()
QByteArray::iterator begin()
QByteArray::const_iterator begin() const
int capacity() const
QByteArray::const_iterator cbegin() const
QByteArray::const_iterator cend() const
void chop(int n)
QByteArray chopped(int len) const
void clear()
int compare(const char *c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare(const QByteArray &a, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QByteArray::const_iterator constBegin() const
const char *constData() const
QByteArray::const_iterator constEnd() const
bool contains(const QByteArray &ba) const
bool contains(char ch) const
bool contains(const char *str) const
int count(const QByteArray &ba) const
int count(char ch) const
int count(const char *str) const
int count() const
QByteArray::const_reverse_iterator crbegin() const
QByteArray::const_reverse_iterator crend() const
char *data()
const char *data() const
QByteArray::iterator end()
QByteArray::const_iterator end() const
bool endsWith(const QByteArray &ba) const
bool endsWith(char ch) const
bool endsWith(const char *str) const
QByteArray &fill(char ch, int size = -1)
char front() const
QByteRef front()
int indexOf(const QByteArray &ba, int from = 0) const
int indexOf(char ch, int from = 0) const
int indexOf(const char *str, int from = 0) const
QByteArray &insert(int i, const QByteArray &ba)
QByteArray &insert(int i, char ch)
QByteArray &insert(int i, int count, char ch)
QByteArray &insert(int i, const char *str)
QByteArray &insert(int i, const char *str, int len)
bool isEmpty() const
bool isLower() const
bool isNull() const
bool isUpper() const
int lastIndexOf(const QByteArray &ba, int from = -1) const
int lastIndexOf(char ch, int from = -1) const
int lastIndexOf(const char *str, 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 pos, int len = -1) const
QByteArray &prepend(const QByteArray &ba)
QByteArray &prepend(char ch)
QByteArray &prepend(int count, char ch)
QByteArray &prepend(const char *str)
QByteArray &prepend(const char *str, int len)
void push_back(const QByteArray &other)
void push_back(char ch)
void push_back(const char *str)
void push_front(const QByteArray &other)
void push_front(char ch)
void push_front(const char *str)
QByteArray::reverse_iterator rbegin()
QByteArray::const_reverse_iterator rbegin() const
QByteArray &remove(int pos, int len)
QByteArray::reverse_iterator rend()
QByteArray::const_reverse_iterator rend() const
QByteArray repeated(int times) const
QByteArray &replace(int pos, int len, const QByteArray &after)
QByteArray &replace(int pos, int len, const char *after)
QByteArray &replace(int pos, int len, const char *after, int alen)
QByteArray &replace(char before, const char *after)
QByteArray &replace(char before, const QByteArray &after)
QByteArray &replace(const char *before, const char *after)
QByteArray &replace(const char *before, int bsize, const char *after, int asize)
QByteArray &replace(const QByteArray &before, const QByteArray &after)
QByteArray &replace(const QByteArray &before, const char *after)
QByteArray &replace(const char *before, const QByteArray &after)
QByteArray &replace(char before, char after)
void reserve(int size)
void resize(int size)
QByteArray right(int len) const
QByteArray rightJustified(int width, char fill = ' ', bool truncate = false) const
QByteArray &setNum(int n, int base = 10)
QByteArray &setNum(short n, int base = 10)
QByteArray &setNum(ushort n, int base = 10)
QByteArray &setNum(uint n, int base = 10)
QByteArray &setNum(qlonglong n, int base = 10)
QByteArray &setNum(qulonglong n, int base = 10)
QByteArray &setNum(float n, char f = 'g', int prec = 6)
QByteArray &setNum(double n, char f = 'g', int prec = 6)
QByteArray &setRawData(const char *data, uint size)
void shrink_to_fit()
QByteArray simplified() const
int size() const
QList<QByteArray> split(char sep) const
void squeeze()
bool startsWith(const QByteArray &ba) const
bool startsWith(char ch) const
bool startsWith(const char *str) const
void swap(QByteArray &other)
QByteArray toBase64() const
QByteArray toBase64(QByteArray::Base64Options options) const
CFDataRef toCFData() const
double toDouble(bool *ok = nullptr) const
float toFloat(bool *ok = nullptr) const
QByteArray toHex() const
QByteArray toHex(char separator) const
int toInt(bool *ok = nullptr, int base = 10) const
long toLong(bool *ok = nullptr, int base = 10) const
qlonglong toLongLong(bool *ok = nullptr, int base = 10) const
QByteArray toLower() const
NSData *toNSData() const
QByteArray toPercentEncoding(const QByteArray &exclude = QByteArray(), const QByteArray &include = QByteArray(), char percent = '%') const
CFDataRef toRawCFData() const
NSData *toRawNSData() const
short toShort(bool *ok = nullptr, int base = 10) const
std::string toStdString() const
uint toUInt(bool *ok = nullptr, int base = 10) const
ulong toULong(bool *ok = nullptr, int base = 10) const
qulonglong toULongLong(bool *ok = nullptr, int base = 10) const
ushort toUShort(bool *ok = nullptr, int base = 10) const
QByteArray toUpper() const
QByteArray trimmed() const
void truncate(int pos)
const char *operator const char *() const
const void *operator const void *() const
bool operator!=(const QString &str) const
QByteArray &operator+=(const QByteArray &ba)
QByteArray &operator+=(char ch)
QByteArray &operator+=(const char *str)
bool operator<(const QString &str) const
bool operator<=(const QString &str) const
QByteArray &operator=(const char *str)
bool operator==(const QString &str) const
bool operator>(const QString &str) const
bool operator>=(const QString &str) const
QByteRef operator[](int i)
char operator[](int i) const
char operator[](uint i) const
QByteRef operator[](uint i)

Static Public Members

QByteArray fromBase64(const QByteArray &base64, QByteArray::Base64Options options)
QByteArray fromBase64(const QByteArray &base64)
QByteArray::FromBase64Result fromBase64Encoding(QByteArray &&base64, QByteArray::Base64Options options = Base64Encoding)
QByteArray::FromBase64Result fromBase64Encoding(const QByteArray &base64, QByteArray::Base64Options options = Base64Encoding)
QByteArray fromCFData(CFDataRef data)
QByteArray fromHex(const QByteArray &hexEncoded)
QByteArray fromNSData(const NSData *data)
QByteArray fromPercentEncoding(const QByteArray &input, char percent = '%')
QByteArray fromRawCFData(CFDataRef data)
QByteArray fromRawData(const char *data, int size)
QByteArray fromRawNSData(const NSData *data)
QByteArray fromStdString(const std::string &str)
QByteArray number(int n, int base = 10)
QByteArray number(uint n, int base = 10)
QByteArray number(qlonglong n, int base = 10)
QByteArray number(qulonglong n, int base = 10)
QByteArray number(double n, char f = 'g', int prec = 6)
quint16 qChecksum(const char *data, uint len)
quint16 qChecksum(const char *data, uint len, Qt::ChecksumType standard)
QByteArray qCompress(const QByteArray &data, int compressionLevel = -1)
QByteArray qCompress(const uchar *data, int nbytes, int compressionLevel = -1)
QByteArray qUncompress(const QByteArray &data)
QByteArray qUncompress(const uchar *data, int nbytes)
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)
int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap)
bool operator!=(const QByteArray &a1, const QByteArray &a2)
bool operator!=(const QByteArray &a1, const char *a2)
bool operator!=(const char *a1, const QByteArray &a2)
const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
const QByteArray operator+(const QByteArray &a1, const char *a2)
const QByteArray operator+(const QByteArray &a1, char a2)
const QByteArray operator+(const char *a1, const QByteArray &a2)
const QByteArray operator+(char a1, const QByteArray &a2)
bool operator<(const QByteArray &a1, const QByteArray &a2)
bool operator<(const QByteArray &a1, const char *a2)
bool operator<(const char *a1, const QByteArray &a2)
QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
bool operator<=(const QByteArray &a1, const QByteArray &a2)
bool operator<=(const QByteArray &a1, const char *a2)
bool operator<=(const char *a1, const QByteArray &a2)
bool operator==(const QByteArray &a1, const QByteArray &a2)
bool operator==(const QByteArray &a1, const char *a2)
bool operator==(const char *a1, const QByteArray &a2)
bool operator>(const QByteArray &a1, const QByteArray &a2)
bool operator>(const QByteArray &a1, const char *a2)
bool operator>(const char *a1, const QByteArray &a2)
bool operator>=(const QByteArray &a1, const QByteArray &a2)
bool operator>=(const QByteArray &a1, const char *a2)
bool operator>=(const char *a1, const QByteArray &a2)
QDataStream &operator>>(QDataStream &in, QByteArray &ba)

Macros

Detailed Description

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 Qt for Embedded Linux).

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.resize(5);
 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]" << Qt::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, but excluding the terminating '\0' added by QByteArray. For example:

 QByteArray ba1("ca\0r\0t");
 ba1.size();                     // Returns 2.
 ba1.constData();                // Returns "ca" with terminating \0.

 QByteArray ba2("ca\0r\0t", 3);
 ba2.size();                     // Returns 3.
 ba2.constData();                // Returns "ca\0" with terminating \0.

 QByteArray ba3("ca\0r\0t", 4);
 ba3.size();                     // Returns 4.
 ba3.constData();                // Returns "ca\0r" with terminating \0.

 const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
 QByteArray ba4(QByteArray::fromRawData(cart, 6));
 ba4.size();                     // Returns 6.
 ba4.constData();                // Returns "ca\0r\0t" without terminating \0.

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 unless the QByteArray was created from a raw data. 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 << Qt::endl;
     ++j;
 }

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 valid pointer (not nullptr) to a '\0' character for a byte array and QByteArray() compares equal to QByteArray(""). We recommend that you always use isEmpty() and avoid isNull().

Maximum size and out-of-memory conditions

The current version of QByteArray is limited to just under 2 GB (2^31 bytes) in size. The exact value is architecture-dependent, since it depends on the overhead required for managing the data block, but is no more than 32 bytes. Raw data blocks are also limited by the use of int type in the current version to 2 GB minus 1 byte.

In case memory allocation fails, QByteArray will throw a std::bad_alloc exception. Out of memory conditions in the Qt containers are the only case where Qt will throw exceptions.

Note that the operating system may impose further limits on applications holding a lot of allocated memory, especially large, contiguous blocks. Such considerations, the configuration of such behavior or any mitigation are outside the scope of the QByteArray API.

Notes on Locale

Number-String Conversions

Functions that perform conversions between numeric data types and strings are performed in the C locale, irrespective of the user's locale settings. Use QString to perform locale-aware conversions between numbers and strings.

8-bit Character Comparisons

In QByteArray, the notion of uppercase and lowercase and of which character is greater than or less than another character is done in the Latin-1 locale. This affects functions that support a case insensitive option or that compare or lowercase or uppercase their arguments. Case insensitive operations and comparisons will be accurate if both strings contain only Latin-1 characters. Functions that this affects include contains(), indexOf(), lastIndexOf(), operator<(), operator<=(), operator>(), operator>=(), isLower(), isUpper(), toLower() and toUpper().

This issue does not apply to QStrings since they represent characters using Unicode.

See also QString and QBitArray.

Member Type Documentation

enum QByteArray::Base64Option
flags QByteArray::Base64Options

This enum contains the options available for encoding and decoding Base64. Base64 is defined by RFC 4648, with the following options:

ConstantValueDescription
QByteArray::Base64Encoding0(default) The regular Base64 alphabet, called simply "base64"
QByteArray::Base64UrlEncoding1An alternate alphabet, called "base64url", which replaces two characters in the alphabet to be more friendly to URLs.
QByteArray::KeepTrailingEquals0(default) Keeps the trailing padding equal signs at the end of the encoded data, so the data is always a size multiple of four.
QByteArray::OmitTrailingEquals2Omits adding the padding equal signs at the end of the encoded data.
QByteArray::IgnoreBase64DecodingErrors0When decoding Base64-encoded data, ignores errors in the input; invalid characters are simply skipped. This enum value has been added in Qt 5.15.
QByteArray::AbortOnBase64DecodingErrors4When decoding Base64-encoded data, stops at the first decoding error. This enum value has been added in Qt 5.15.

QByteArray::fromBase64Encoding() and QByteArray::fromBase64() ignore the KeepTrailingEquals and OmitTrailingEquals options. If the IgnoreBase64DecodingErrors option is specified, they will not flag errors in case trailing equal signs are missing or if there are too many of them. If instead the AbortOnBase64DecodingErrors is specified, then the input must either have no padding or have the correct amount of equal signs.

This enum was introduced or modified in Qt 5.2.

The Base64Options type is a typedef for QFlags<Base64Option>. It stores an OR combination of Base64Option values.

typedef QByteArray::const_iterator

This typedef provides an STL-style const iterator for QByteArray.

See also QByteArray::const_reverse_iterator and QByteArray::iterator.

typedef QByteArray::const_reverse_iterator

This typedef provides an STL-style const reverse iterator for QByteArray.

This typedef was introduced in Qt 5.6.

See also QByteArray::reverse_iterator and QByteArray::const_iterator.

typedef QByteArray::iterator

This typedef provides an STL-style non-const iterator for QByteArray.

See also QByteArray::reverse_iterator and QByteArray::const_iterator.

typedef QByteArray::reverse_iterator

This typedef provides an STL-style non-const reverse iterator for QByteArray.

This typedef was introduced in Qt 5.6.

See also QByteArray::const_reverse_iterator and QByteArray::iterator.

Member Function Documentation

[static] QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, QByteArray::Base64Options options = Base64Encoding)

[static] QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, QByteArray::Base64Options options = Base64Encoding)

This is an overloaded function.

Decodes the Base64 array base64, using the options defined by options. If options contains IgnoreBase64DecodingErrors (the default), the input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters. If options contains AbortOnBase64DecodingErrors, then decoding will stop at the first invalid character.

For example:

 void process(const QByteArray &);

 if (auto result = QByteArray::fromBase64Encoding(encodedData))
     process(*result);

The algorithm used to decode Base64-encoded data is defined in RFC 4648.

Returns a QByteArrayFromBase64Result object, containing the decoded data and a flag telling whether decoding was successful. If the AbortOnBase64DecodingErrors option was passed and the input data was invalid, it is unspecified what the decoded data contains.

This function was introduced in Qt 5.15.

See also toBase64().

QByteArray::QByteArray(QByteArray &&other)

Move-constructs a QByteArray instance, making it point at the same object that other was pointing to.

This function was introduced in Qt 5.2.

QByteArray::QByteArray(const QByteArray &other)

Constructs a copy of other.

This operation takes constant time, because QByteArray is implicitly shared. This makes returning a QByteArray from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), taking linear time.

See also operator=().

QByteArray::QByteArray(int size, char ch)

Constructs a byte array of size size with every byte set to character ch.

See also fill().

QByteArray::QByteArray(const char *data, int size = -1)

Constructs a byte array containing the first size bytes of array data.

If data is 0, a null byte array is constructed.

If size is negative, data is assumed to point to a '\0'-terminated string and its length is determined dynamically. The terminating \0 character is not considered part of the byte array.

QByteArray makes a deep copy of the string data.

See also fromRawData().

QByteArray::QByteArray()

Constructs an empty byte array.

See also isEmpty().

QByteArray &QByteArray::operator=(QByteArray &&other)

Move-assigns other to this QByteArray instance.

This function was introduced in Qt 5.2.

QByteArray &QByteArray::operator=(const QByteArray &other)

Assigns other to this byte array and returns a reference to this byte array.

QByteArray::~QByteArray()

Destroys the byte array.

QByteArray &QByteArray::append(const QByteArray &ba)

Appends the byte array ba onto the end of this byte array.

Example:

 QByteArray x("free");
 QByteArray y("dom");
 x.append(y);
 // x == "freedom"

This is the same as insert(size(), ba).

Note: QByteArray is an implicitly shared class. Consequently, if you append to an empty byte array, then the byte array will just share the data held in ba. In this case, no copying of data is done, taking constant time. If a shared instance is modified, it will be copied (copy-on-write), taking linear time.

If the byte array being appended to is not empty, a deep copy of the data is performed, taking linear time.

This operation typically does not suffer from allocation overhead, because QByteArray preallocates extra space at the end of the data so that it may grow without reallocating for each append operation.

See also operator+=(), prepend(), and insert().

QByteArray &QByteArray::append(char ch)

This is an overloaded function.

Appends the character ch to this byte array.

QByteArray &QByteArray::append(int count, char ch)

This is an overloaded function.

Appends count copies of character ch to this byte array and returns a reference to this byte array.

If count is negative or zero nothing is appended to the byte array.

This function was introduced in Qt 5.7.

QByteArray &QByteArray::append(const char *str)

This is an overloaded function.

Appends the string str to this byte array.

QByteArray &QByteArray::append(const char *str, int len)

This function overloads append().

Appends the first len characters of the string str to this byte array and returns a reference to this byte array.

If len is negative, the length of the string will be determined automatically using qstrlen(). If len is zero or str is null, nothing is appended to the byte array. Ensure that len is not longer than str.

char QByteArray::at(int i) const

Returns the character at index position i in the byte array.

i must be a valid index position in the byte array (i.e., 0 <= i < size()).

See also operator[]().

char QByteArray::back() const

Returns the last character in the byte array. Same as at(size() - 1).

This function is provided for STL compatibility.

Warning: Calling this function on an empty byte array constitutes undefined behavior.

This function was introduced in Qt 5.10.

See also front(), at(), and operator[]().

QByteRef QByteArray::back()

Returns a reference to the last character in the byte array. Same as operator[](size() - 1).

This function is provided for STL compatibility.

Warning: Calling this function on an empty byte array constitutes undefined behavior.

This function was introduced in Qt 5.10.

See also front(), at(), and operator[]().

QByteArray::iterator QByteArray::begin()

Returns an STL-style iterator pointing to the first character in the byte-array.

See also constBegin() and end().

QByteArray::const_iterator QByteArray::begin() const

This function overloads begin().

int QByteArray::capacity() const

Returns the maximum number of bytes that can be stored in the byte array without forcing a reallocation.

The sole purpose of this function is to provide a means of fine tuning QByteArray's memory usage. In general, you will rarely ever need to call this function. If you want to know how many bytes are in the byte array, call size().

See also reserve() and squeeze().

QByteArray::const_iterator QByteArray::cbegin() const

Returns a const STL-style iterator pointing to the first character in the byte-array.

This function was introduced in Qt 5.0.

See also begin() and cend().

QByteArray::const_iterator QByteArray::cend() const

Returns a const STL-style iterator pointing to the imaginary character after the last character in the list.

This function was introduced in Qt 5.0.

See also cbegin() and end().

void QByteArray::chop(int n)

Removes n bytes from the end of the byte array.

If n is greater than size(), the result is an empty byte array.

Example:

 QByteArray ba("STARTTLS\r\n");
 ba.chop(2);                 // ba == "STARTTLS"

See also truncate(), resize(), and left().

QByteArray QByteArray::chopped(int len) const

Returns a byte array that contains the leftmost size() - len bytes of this byte array.

Note: The behavior is undefined if len is negative or greater than size().

This function was introduced in Qt 5.10.

See also endsWith(), left(), right(), mid(), chop(), and truncate().

void QByteArray::clear()

Clears the contents of the byte array and makes it null.

See also resize() and isNull().

int QByteArray::compare(const char *c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns an integer less than, equal to, or greater than zero depending on whether this QByteArray sorts before, at the same position, or after the string pointed to by c. The comparison is performed according to case sensitivity cs.

This function was introduced in Qt 5.12.

See also operator==.

int QByteArray::compare(const QByteArray &a, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This is an overloaded function.

Returns an integer less than, equal to, or greater than zero depending on whether this QByteArray sorts before, at the same position, or after the QByteArray a. The comparison is performed according to case sensitivity cs.

This function was introduced in Qt 5.12.

See also operator==.

QByteArray::const_iterator QByteArray::constBegin() const

Returns a const STL-style iterator pointing to the first character in the byte-array.

See also begin() and constEnd().

const char *QByteArray::constData() const

Returns a pointer to the data stored in the byte array. The pointer can be used to access the bytes that compose the array. The data is '\0'-terminated unless the QByteArray object was created from raw data. The pointer remains valid as long as the byte array isn't reallocated or destroyed.

This function is mostly useful to pass a byte array to a function that accepts a const char *.

Note: A QByteArray can store any byte values including '\0's, but most functions that take char * arguments assume that the data ends at the first '\0' they encounter.

See also data(), operator[](), and fromRawData().

QByteArray::const_iterator QByteArray::constEnd() const

Returns a const STL-style iterator pointing to the imaginary character after the last character in the list.

See also constBegin() and end().

bool QByteArray::contains(const QByteArray &ba) const

Returns true if the byte array contains an occurrence of the byte array ba; otherwise returns false.

See also indexOf() and count().

bool QByteArray::contains(char ch) const

This is an overloaded function.

Returns true if the byte array contains the character ch; otherwise returns false.

bool QByteArray::contains(const char *str) const

This is an overloaded function.

Returns true if the byte array contains the string str; otherwise returns false.

int QByteArray::count(const QByteArray &ba) const

Returns the number of (potentially overlapping) occurrences of byte array ba in this byte array.

See also contains() and indexOf().

int QByteArray::count(char ch) const

This is an overloaded function.

Returns the number of occurrences of character ch in the byte array.

See also contains() and indexOf().

int QByteArray::count(const char *str) const

This is an overloaded function.

Returns the number of (potentially overlapping) occurrences of string str in the byte array.

int QByteArray::count() const

This is an overloaded function.

Same as size().

QByteArray::const_reverse_iterator QByteArray::crbegin() const

Returns a const STL-style reverse iterator pointing to the first character in the byte-array, in reverse order.

This function was introduced in Qt 5.6.

See also begin(), rbegin(), and rend().

QByteArray::const_reverse_iterator QByteArray::crend() const

Returns a const STL-style reverse iterator pointing to one past the last character in the byte-array, in reverse order.

This function was introduced in Qt 5.6.

See also end(), rend(), and rbegin().

char *QByteArray::data()

Returns a pointer to the data stored in the byte array. The pointer can be used to access and modify the bytes that compose the array. The data is '\0'-terminated, i.e. the number of bytes in the returned character string is size() + 1 for the '\0' terminator.

Example:

 QByteArray ba("Hello world");
 char *data = ba.data();
 while (*data) {
     cout << "[" << *data << "]" << Qt::endl;
     ++data;
 }

The pointer remains valid as long as the byte array isn't reallocated or destroyed. For read-only access, constData() is faster because it never causes a deep copy to occur.

This function is mostly useful to pass a byte array to a function that accepts a const char *.

The following example makes a copy of the char* returned by data(), but it will corrupt the heap and cause a crash because it does not allocate a byte for the '\0' at the end:

 QString tmp = "test";
 QByteArray text = tmp.toLocal8Bit();
 char *data = new char[text.size()];
 strcpy(data, text.data());
 delete [] data;

This one allocates the correct amount of space:

 QString tmp = "test";
 QByteArray text = tmp.toLocal8Bit();
 char *data = new char[text.size() + 1];
 strcpy(data, text.data());
 delete [] data;

Note: A QByteArray can store any byte values including '\0's, but most functions that take char * arguments assume that the data ends at the first '\0' they encounter.

See also constData() and operator[]().

const char *QByteArray::data() const

This is an overloaded function.

QByteArray::iterator QByteArray::end()

Returns an STL-style iterator pointing to the imaginary character after the last character in the byte-array.

See also begin() and constEnd().

QByteArray::const_iterator QByteArray::end() const

This function overloads end().

bool QByteArray::endsWith(const QByteArray &ba) const

Returns true if this byte array ends with byte array ba; otherwise returns false.

Example:

 QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
 if (url.endsWith(".html"))
     ...

See also startsWith() and right().

bool QByteArray::endsWith(char ch) const

This is an overloaded function.

Returns true if this byte array ends with character ch; otherwise returns false.

bool QByteArray::endsWith(const char *str) const

This is an overloaded function.

Returns true if this byte array ends with string str; otherwise returns false.

QByteArray &QByteArray::fill(char ch, int size = -1)

Sets every byte in the byte array to character ch. If size is different from -1 (the default), the byte array is resized to size size beforehand.

Example:

 QByteArray ba("Istambul");
 ba.fill('o');
 // ba == "oooooooo"

 ba.fill('X', 2);
 // ba == "XX"

See also resize().

[static] QByteArray QByteArray::fromBase64(const QByteArray &base64, QByteArray::Base64Options options)

This is an overloaded function.

Returns a decoded copy of the Base64 array base64, using the options defined by options. If options contains IgnoreBase64DecodingErrors (the default), the input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters. If options contains AbortOnBase64DecodingErrors, then decoding will stop at the first invalid character.

For example:

 QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
 QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"

The algorithm used to decode Base64-encoded data is defined in RFC 4648.

Returns the decoded data, or, if the AbortOnBase64DecodingErrors option was passed and the input data was invalid, an empty byte array.

Note: The fromBase64Encoding() function is recommended in new code.

This function was introduced in Qt 5.2.

See also toBase64() and fromBase64Encoding().

[static] QByteArray QByteArray::fromBase64(const QByteArray &base64)

This is an overloaded function.

Returns a decoded copy of the Base64 array base64. Input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters.

For example:

 QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
 text.data();            // returns "Qt is great!"

The algorithm used to decode Base64-encoded data is defined in RFC 4648.

Note: The fromBase64Encoding() function is recommended in new code.

See also toBase64() and fromBase64Encoding().

[static] QByteArray QByteArray::fromCFData(CFDataRef data)

Constructs a new QByteArray containing a copy of the CFData data.

This function was introduced in Qt 5.3.

See also fromRawCFData(), fromRawData(), toRawCFData(), and toCFData().

[static] QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)

Returns a decoded copy of the hex encoded array hexEncoded. Input is not checked for validity; invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters.

For example:

 QByteArray text = QByteArray::fromHex("517420697320677265617421");
 text.data();            // returns "Qt is great!"

See also toHex().

[static] QByteArray QByteArray::fromNSData(const NSData *data)

Constructs a new QByteArray containing a copy of the NSData data.

This function was introduced in Qt 5.3.

See also fromRawNSData(), fromRawData(), toNSData(), and toRawNSData().

[static] QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent = '%')

Returns a decoded copy of the URI/URL-style percent-encoded input. The percent parameter allows you to replace the '%' character for another (for instance, '_' or '=').

For example:

 QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
 text.data();            // returns "Qt is great!"

Note: Given invalid input (such as a string containing the sequence "%G5", which is not a valid hexadecimal number) the output will be invalid as well. As an example: the sequence "%G5" could be decoded to 'W'.

This function was introduced in Qt 4.4.

See also toPercentEncoding() and QUrl::fromPercentEncoding().

[static] QByteArray QByteArray::fromRawCFData(CFDataRef data)

Constructs a QByteArray that uses the bytes of the CFData data.

The data's bytes are not copied.

The caller guarantees that the CFData will not be deleted or modified as long as this QByteArray object exists.

This function was introduced in Qt 5.3.

See also fromCFData(), fromRawData(), toRawCFData(), and toCFData().

[static] QByteArray QByteArray::fromRawData(const char *data, int size)

Constructs a QByteArray that uses the first size bytes of the data array. The bytes are not copied. The QByteArray will contain the data pointer. The caller guarantees that data will not be deleted or modified as long as this QByteArray and any copies of it exist that have not been modified. In other words, because QByteArray is an implicitly shared class and the instance returned by this function contains the data pointer, the caller must not delete data or modify it directly as long as the returned QByteArray and any copies exist. However, QByteArray does not take ownership of data, so the QByteArray destructor will never delete the raw data, even when the last QByteArray referring to data is destroyed.

A subsequent attempt to modify the contents of the returned QByteArray or any copy made from it will cause it to create a deep copy of the data array before doing the modification. This ensures that the raw data array itself will never be modified by QByteArray.

Here is an example of how to read data using a QDataStream on raw data in memory without copying the raw data into a QByteArray:

  static const char mydata[] = {
     '\x00', '\x00', '\x03', '\x84', '\x78', '\x9c', '\x3b', '\x76',
     '\xec', '\x18', '\xc3', '\x31', '\x0a', '\xf1', '\xcc', '\x99',
     ...
     '\x6d', '\x5b'
 };

 QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
 QDataStream in(&data, QIODevice::ReadOnly);
 ...

Warning: A byte array created with fromRawData() is not '\0'-terminated, unless the raw data contains a 0 character at position size. While that does not matter for QDataStream or functions like indexOf(), passing the byte array to a function accepting a const char * expected to be '\0'-terminated will fail.

See also setRawData(), data(), and constData().

[static] QByteArray QByteArray::fromRawNSData(const NSData *data)

Constructs a QByteArray that uses the bytes of the NSData data.

The data's bytes are not copied.

The caller guarantees that the NSData will not be deleted or modified as long as this QByteArray object exists.

This function was introduced in Qt 5.3.

See also fromNSData(), fromRawData(), toRawNSData(), and toNSData().

[static] QByteArray QByteArray::fromStdString(const std::string &str)

Returns a copy of the str string as a QByteArray.

This function was introduced in Qt 5.4.

See also toStdString() and QString::fromStdString().

char QByteArray::front() const

Returns the first character in the byte array. Same as at(0).

This function is provided for STL compatibility.

Warning: Calling this function on an empty byte array constitutes undefined behavior.

This function was introduced in Qt 5.10.

See also back(), at(), and operator[]().

QByteRef QByteArray::front()

Returns a reference to the first character in the byte array. Same as operator[](0).

This function is provided for STL compatibility.

Warning: Calling this function on an empty byte array constitutes undefined behavior.

This function was introduced in Qt 5.10.

See also back(), at(), and operator[]().

int QByteArray::indexOf(const QByteArray &ba, int from = 0) const

Returns the index position of the first occurrence of the byte array ba in this byte array, searching forward from index position from. Returns -1 if ba could not be found.

Example:

 QByteArray x("sticky question");
 QByteArray y("sti");
 x.indexOf(y);               // returns 0
 x.indexOf(y, 1);            // returns 10
 x.indexOf(y, 10);           // returns 10
 x.indexOf(y, 11);           // returns -1

See also lastIndexOf(), contains(), and count().

int QByteArray::indexOf(char ch, int from = 0) const

This is an overloaded function.

Returns the index position of the first occurrence of the character ch in the byte array, searching forward from index position from. Returns -1 if ch could not be found.

Example:

 QByteArray ba("ABCBA");
 ba.indexOf("B");            // returns 1
 ba.indexOf("B", 1);         // returns 1
 ba.indexOf("B", 2);         // returns 3
 ba.indexOf("X");            // returns -1

See also lastIndexOf() and contains().

int QByteArray::indexOf(const char *str, int from = 0) const

This is an overloaded function.

Returns the index position of the first occurrence of the string str in the byte array, searching forward from index position from. Returns -1 if str could not be found.

QByteArray &QByteArray::insert(int i, const QByteArray &ba)

Inserts the byte array ba at index position i and returns a reference to this byte array.

Example:

 QByteArray ba("Meal");
 ba.insert(1, QByteArray("ontr"));
 // ba == "Montreal"

See also append(), prepend(), replace(), and remove().

QByteArray &QByteArray::insert(int i, char ch)

This is an overloaded function.

Inserts character ch at index position i in the byte array. If i is greater than size(), the array is first extended using resize().

QByteArray &QByteArray::insert(int i, int count, char ch)

This is an overloaded function.

Inserts count copies of character ch at index position i in the byte array.

If i is greater than size(), the array is first extended using resize().

This function was introduced in Qt 5.7.

QByteArray &QByteArray::insert(int i, const char *str)

This is an overloaded function.

Inserts the string str at position i in the byte array.

If i is greater than size(), the array is first extended using resize().

QByteArray &QByteArray::insert(int i, const char *str, int len)

This is an overloaded function.

Inserts len bytes of the string str at position i in the byte array.

If i is greater than size(), the array is first extended using resize().

This function was introduced in Qt 4.6.

bool QByteArray::isEmpty() const

Returns true if the byte array has size 0; otherwise returns false.

Example:

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

See also size().

bool QByteArray::isLower() const

Returns true if this byte array contains only lowercase letters, otherwise returns false. The byte array is interpreted as a Latin-1 encoded string.

This function was introduced in Qt 5.12.

See also isUpper() and toLower().

bool QByteArray::isNull() const

Returns true if this byte array is null; otherwise returns false.

Example:

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

Qt makes a distinction between null byte arrays and empty byte arrays for historical reasons. For most applications, what matters is whether or not a byte array contains any data, and this can be determined using isEmpty().

See also isEmpty().

bool QByteArray::isUpper() const

Returns true if this byte array contains only uppercase letters, otherwise returns false. The byte array is interpreted as a Latin-1 encoded string.

This function was introduced in Qt 5.12.

See also isLower() and toUpper().

int QByteArray::lastIndexOf(const QByteArray &ba, int from = -1) const

Returns the index position of the last occurrence of the byte array ba in this byte array, searching backward from index position from. If from is -1 (the default), the search starts at the last byte. Returns -1 if ba could not be found.

Example:

 QByteArray x("crazy azimuths");
 QByteArray y("az");
 x.lastIndexOf(y);           // returns 6
 x.lastIndexOf(y, 6);        // returns 6
 x.lastIndexOf(y, 5);        // returns 2
 x.lastIndexOf(y, 1);        // returns -1

See also indexOf(), contains(), and count().

int QByteArray::lastIndexOf(char ch, int from = -1) const

This is an overloaded function.

Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from. If from is -1 (the default), the search starts at the last (size() - 1) byte. Returns -1 if ch could not be found.

Example:

 QByteArray ba("ABCBA");
 ba.lastIndexOf("B");        // returns 3
 ba.lastIndexOf("B", 3);     // returns 3
 ba.lastIndexOf("B", 2);     // returns 1
 ba.lastIndexOf("X");        // returns -1

See also indexOf() and contains().

int QByteArray::lastIndexOf(const char *str, int from = -1) const

This is an overloaded function.

Returns the index position of the last occurrence of the string str in the byte array, searching backward from index position from. If from is -1 (the default), the search starts at the last (size() - 1) byte. Returns -1 if str could not be found.

QByteArray QByteArray::left(int len) const

Returns a byte array that contains the leftmost len bytes of this byte array.

The entire byte array is returned if len is greater than size().

Example:

 QByteArray x("Pineapple");
 QByteArray y = x.left(4);
 // y == "Pine"

See also startsWith(), right(), mid(), chopped(), chop(), and truncate().

QByteArray QByteArray::leftJustified(int width, char fill = ' ', bool truncate = false) const

Returns a byte array of size width that contains this byte array padded by the fill character.

If truncate is false and the size() of the byte array is more than width, then the returned byte array is a copy of this byte array.

If truncate is true and the size() of the byte array is more than width, then any bytes in a copy of the byte array after position width are removed, and the copy is returned.

Example:

 QByteArray x("apple");
 QByteArray y = x.leftJustified(8, '.');   // y == "apple..."

See also rightJustified().

int QByteArray::length() const

Same as size().

QByteArray QByteArray::mid(int pos, int len = -1) const

Returns a byte array containing len bytes from this byte array, starting at position pos.

If len is -1 (the default), or pos + len >= size(), returns a byte array containing all bytes starting at position pos until the end of the byte array.

Example:

 QByteArray x("Five pineapples");
 QByteArray y = x.mid(5, 4);     // y == "pine"
 QByteArray z = x.mid(5);        // z == "pineapples"

See also left(), right(), chopped(), chop(), and truncate().

[static] QByteArray QByteArray::number(int n, int base = 10)

Returns a byte array containing the string equivalent of the number n to base base (10 by default). The base can be any value between 2 and 36.

Example:

 int n = 63;
 QByteArray::number(n);              // returns "63"
 QByteArray::number(n, 16);          // returns "3f"
 QByteArray::number(n, 16).toUpper();  // returns "3F"

Note: The format of the number is not localized; the default C locale is used irrespective of the user's locale.

See also setNum() and toInt().

[static] QByteArray QByteArray::number(uint n, int base = 10)

This is an overloaded function.

See also toUInt().

[static] QByteArray QByteArray::number(qlonglong n, int base = 10)

This is an overloaded function.

See also toLongLong().

[static] QByteArray QByteArray::number(qulonglong n, int base = 10)

This is an overloaded function.

See also toULongLong().

[static] QByteArray QByteArray::number(double n, char f = 'g', int prec = 6)

This is an overloaded function.

Returns a byte array that contains the printed value of n, formatted in format f with precision prec.

Argument n is formatted according to the f format specified, which is g by default, and can be any of the following:

FormatMeaning
eformat as [-]9.9e[+|-]999
Eformat as [-]9.9E[+|-]999
fformat as [-]9.9
guse e or f format, whichever is the most concise
Guse E or f format, whichever is the most concise

With 'e', 'E', and 'f', prec is the number of digits after the decimal point. With 'g' and 'G', prec is the maximum number of significant digits (trailing zeroes are omitted).

 QByteArray ba = QByteArray::number(12.3456, 'E', 3);
 // ba == 1.235E+01

Note: The format of the number is not localized; the default C locale is used irrespective of the user's locale.

See also toDouble().

QByteArray &QByteArray::prepend(const QByteArray &ba)

Prepends the byte array ba to this byte array and returns a reference to this byte array.

Example:

 QByteArray x("ship");
 QByteArray y("air");
 x.prepend(y);
 // x == "airship"

This is the same as insert(0, ba).

Note: QByteArray is an implicitly shared class. Consequently, if you prepend to an empty byte array, then the byte array will just share the data held in ba. In this case, no copying of data is done, taking constant time. If a shared instance is modified, it will be copied (copy-on-write), taking linear time.

If the byte array being prepended to is not empty, a deep copy of the data is performed, taking linear time.

See also append() and insert().

QByteArray &QByteArray::prepend(char ch)

This is an overloaded function.

Prepends the character ch to this byte array.

QByteArray &QByteArray::prepend(int count, char ch)

This is an overloaded function.

Prepends count copies of character ch to this byte array.

This function was introduced in Qt 5.7.

QByteArray &QByteArray::prepend(const char *str)

This is an overloaded function.

Prepends the string str to this byte array.

QByteArray &QByteArray::prepend(const char *str, int len)

This is an overloaded function.

Prepends len bytes of the string str to this byte array.

This function was introduced in Qt 4.6.

void QByteArray::push_back(const QByteArray &other)

This function is provided for STL compatibility. It is equivalent to append(other).

void QByteArray::push_back(char ch)

This is an overloaded function.

Same as append(ch).

void QByteArray::push_back(const char *str)

This is an overloaded function.

Same as append(str).

void QByteArray::push_front(const QByteArray &other)

This function is provided for STL compatibility. It is equivalent to prepend(other).

void QByteArray::push_front(char ch)

This is an overloaded function.

Same as prepend(ch).

void QByteArray::push_front(const char *str)

This is an overloaded function.

Same as prepend(str).

QByteArray::reverse_iterator QByteArray::rbegin()

Returns a STL-style reverse iterator pointing to the first character in the byte-array, in reverse order.

This function was introduced in Qt 5.6.

See also begin(), crbegin(), and rend().

QByteArray::const_reverse_iterator QByteArray::rbegin() const

This is an overloaded function.

This function was introduced in Qt 5.6.

QByteArray &QByteArray::remove(int pos, int len)

Removes len bytes from the array, starting at index position pos, and returns a reference to the array.

If pos is out of range, nothing happens. If pos is valid, but pos + len is larger than the size of the array, the array is truncated at position pos.

Example:

 QByteArray ba("Montreal");
 ba.remove(1, 4);
 // ba == "Meal"

See also insert() and replace().

QByteArray::reverse_iterator QByteArray::rend()

Returns a STL-style reverse iterator pointing to one past the last character in the byte-array, in reverse order.

This function was introduced in Qt 5.6.

See also end(), crend(), and rbegin().

QByteArray::const_reverse_iterator QByteArray::rend() const

This is an overloaded function.

This function was introduced in Qt 5.6.

QByteArray QByteArray::repeated(int times) const

Returns a copy of this byte array repeated the specified number of times.

If times is less than 1, an empty byte array is returned.

Example:

 QByteArray ba("ab");
 ba.repeated(4);             // returns "abababab"

This function was introduced in Qt 4.5.

QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)

Replaces len bytes from index position pos with the byte array after, and returns a reference to this byte array.

Example:

 QByteArray x("Say yes!");
 QByteArray y("no");
 x.replace(4, 3, y);
 // x == "Say no!"

See also insert() and remove().

QByteArray &QByteArray::replace(int pos, int len, const char *after)

This is an overloaded function.

Replaces len bytes from index position pos with the '\0'-terminated string after.

Notice: this can change the length of the byte array.

QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)

This is an overloaded function.

Replaces len bytes from index position pos with alen bytes from the string after. after is allowed to have '\0' characters.

This function was introduced in Qt 4.7.

QByteArray &QByteArray::replace(char before, const char *after)

This is an overloaded function.

Replaces every occurrence of the character before with the string after.

QByteArray &QByteArray::replace(char before, const QByteArray &after)

This is an overloaded function.

Replaces every occurrence of the character before with the byte array after.

QByteArray &QByteArray::replace(const char *before, const char *after)

This is an overloaded function.

Replaces every occurrence of the string before with the string after.

QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)

This is an overloaded function.

Replaces every occurrence of the string before with the string after. Since the sizes of the strings are given by bsize and asize, they may contain zero characters and do not need to be '\0'-terminated.

QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)

This is an overloaded function.

Replaces every occurrence of the byte array before with the byte array after.

Example:

 QByteArray ba("colour behaviour flavour neighbour");
 ba.replace(QByteArray("ou"), QByteArray("o"));
 // ba == "color behavior flavor neighbor"

QByteArray &QByteArray::replace(const QByteArray &before, const char *after)

This is an overloaded function.

Replaces every occurrence of the byte array before with the string after.

QByteArray &QByteArray::replace(const char *before, const QByteArray &after)

This is an overloaded function.

Replaces every occurrence of the string before with the byte array after.

QByteArray &QByteArray::replace(char before, char after)

This is an overloaded function.

Replaces every occurrence of the character before with the character after.

void QByteArray::reserve(int size)

Attempts to allocate memory for at least size bytes. If you know in advance how large the byte array will be, you can call this function, and if you call resize() often you are likely to get better performance. If size is an underestimate, the worst that will happen is that the QByteArray will be a bit slower.

The sole purpose of this function is to provide a means of fine tuning QByteArray's memory usage. In general, you will rarely ever need to call this function. If you want to change the size of the byte array, call resize().

See also squeeze() and capacity().

void QByteArray::resize(int size)

Sets the size of the byte array to size bytes.

If size is greater than the current size, the byte array is extended to make it size bytes with the extra bytes added to the end. The new bytes are uninitialized.

If size is less than the current size, bytes are removed from the end.

See also size() and truncate().

Returns a byte array that contains the rightmost len bytes of this byte array.

The entire byte array is returned if len is greater than size().

Example:

 QByteArray x("Pineapple");
 QByteArray y = x.right(5);
 // y == "apple"

See also endsWith(), left(), mid(), chopped(), chop(), and truncate().

QByteArray QByteArray::rightJustified(int width, char fill = ' ', bool truncate = false) const

Returns a byte array of size width that contains the fill character followed by this byte array.

If truncate is false and the size of the byte array is more than width, then the returned byte array is a copy of this byte array.

If truncate is true and the size of the byte array is more than width, then the resulting byte array is truncated at position width.

Example:

 QByteArray x("apple");
 QByteArray y = x.rightJustified(8, '.');    // y == "...apple"

See also leftJustified().

QByteArray &QByteArray::setNum(int n, int base = 10)

Sets the byte array to the printed value of n in base base (10 by default) and returns a reference to the byte array. The base can be any value between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

Example:

 QByteArray ba;
 int n = 63;
 ba.setNum(n);           // ba == "63"
 ba.setNum(n, 16);       // ba == "3f"

Note: The format of the number is not localized; the default C locale is used irrespective of the user's locale.

See also number() and toInt().

QByteArray &QByteArray::setNum(short n, int base = 10)

This is an overloaded function.

See also toShort().

QByteArray &QByteArray::setNum(ushort n, int base = 10)

This is an overloaded function.

See also toUShort().

QByteArray &QByteArray::setNum(uint n, int base = 10)

This is an overloaded function.

See also toUInt().

QByteArray &QByteArray::setNum(qlonglong n, int base = 10)

This is an overloaded function.

See also toLongLong().

QByteArray &QByteArray::setNum(qulonglong n, int base = 10)

This is an overloaded function.

See also toULongLong().

QByteArray &QByteArray::setNum(float n, char f = 'g', int prec = 6)

This is an overloaded function.

Sets the byte array to the printed value of n, formatted in format f with precision prec, and returns a reference to the byte array.

Note: The format of the number is not localized; the default C locale is used irrespective of the user's locale.

See also toFloat().

QByteArray &QByteArray::setNum(double n, char f = 'g', int prec = 6)

This is an overloaded function.

Sets the byte array to the printed value of n, formatted in format f with precision prec, and returns a reference to the byte array.

The format f can be any of the following:

FormatMeaning
eformat as [-]9.9e[+|-]999
Eformat as [-]9.9E[+|-]999
fformat as [-]9.9
guse e or f format, whichever is the most concise
Guse E or f format, whichever is the most concise

With 'e', 'E', and 'f', prec is the number of digits after the decimal point. With 'g' and 'G', prec is the maximum number of significant digits (trailing zeroes are omitted).

Note: The format of the number is not localized; the default C locale is used irrespective of the user's locale.

See also toDouble().

QByteArray &QByteArray::setRawData(const char *data, uint size)

Resets the QByteArray to use the first size bytes of the data array. The bytes are not copied. The QByteArray will contain the data pointer. The caller guarantees that data will not be deleted or modified as long as this QByteArray and any copies of it exist that have not been modified.

This function can be used instead of fromRawData() to re-use existing QByteArray objects to save memory re-allocations.

This function was introduced in Qt 4.7.

See also fromRawData(), data(), and constData().

void QByteArray::shrink_to_fit()

This function is provided for STL compatibility. It is equivalent to squeeze().

This function was introduced in Qt 5.10.

QByteArray QByteArray::simplified() const

Returns a byte array that has whitespace removed from the start and the end, and which has each sequence of internal whitespace replaced with a single space.

Whitespace means any character for which the standard C++ isspace() function returns true in the C locale. This includes the ASCII isspace() function returns true in the C locale. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

 QByteArray ba("  lots\t of\nwhitespace\r\n ");
 ba = ba.simplified();
 // ba == "lots of whitespace";

See also trimmed().

int QByteArray::size() const

Returns the number of bytes in this byte array.

The last byte in the byte array is at position size() - 1. In addition, QByteArray ensures that the byte at position size() is always '\0', so that you can use the return value of data() and constData() as arguments to functions that expect '\0'-terminated strings. If the QByteArray object was created from a raw data that didn't include the trailing null-termination character then QByteArray doesn't add it automaticall unless the deep copy is created.

Example:

 QByteArray ba("Hello");
 int n = ba.size();          // n == 5
 ba.data()[0];               // returns 'H'
 ba.data()[4];               // returns 'o'
 ba.data()[5];               // returns '\0'

See also isEmpty() and resize().

QList<QByteArray> QByteArray::split(char sep) const

Splits the byte array into subarrays wherever sep occurs, and returns the list of those arrays. If sep does not match anywhere in the byte array, split() returns a single-element list containing this byte array.

void QByteArray::squeeze()

Releases any memory not required to store the array's data.

The sole purpose of this function is to provide a means of fine tuning QByteArray's memory usage. In general, you will rarely ever need to call this function.

See also reserve() and capacity().

bool QByteArray::startsWith(const QByteArray &ba) const

Returns true if this byte array starts with byte array ba; otherwise returns false.

Example:

 QByteArray url("ftp://ftp.qt-project.org/");
 if (url.startsWith("ftp:"))
     ...

See also endsWith() and left().

bool QByteArray::startsWith(char ch) const

This is an overloaded function.

Returns true if this byte array starts with character ch; otherwise returns false.

bool QByteArray::startsWith(const char *str) const

This is an overloaded function.

Returns true if this byte array starts with string str; otherwise returns false.

void QByteArray::swap(QByteArray &other)

Swaps byte array other with this byte array. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

QByteArray QByteArray::toBase64() const

Returns a copy of the byte array, encoded as Base64.

 QByteArray text("Qt is great!");
 text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"

The algorithm used to encode Base64-encoded data is defined in RFC 4648.

See also fromBase64().

QByteArray QByteArray::toBase64(QByteArray::Base64Options options) const

This is an overloaded function.

Returns a copy of the byte array, encoded using the options options.

 QByteArray text("<p>Hello?</p>");
 text.toBase64(QByteArray::Base64Encoding | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
 text.toBase64(QByteArray::Base64Encoding);                                       // returns "PHA+SGVsbG8/PC9wPg=="
 text.toBase64(QByteArray::Base64UrlEncoding);                                    // returns "PHA-SGVsbG8_PC9wPg=="
 text.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"

The algorithm used to encode Base64-encoded data is defined in RFC 4648.

This function was introduced in Qt 5.2.

See also fromBase64().

CFDataRef QByteArray::toCFData() const

Creates a CFData from a QByteArray. The caller owns the CFData object and is responsible for releasing it.

This function was introduced in Qt 5.3.

See also toRawCFData(), fromCFData(), fromRawCFData(), and fromRawData().

double QByteArray::toDouble(bool *ok = nullptr) const

Returns the byte array converted to a double value.

Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

 QByteArray string("1234.56");
 bool ok;
 double a = string.toDouble(&ok);   // a == 1234.56, ok == true

 string = "1234.56 Volt";
 a = str.toDouble(&ok);             // a == 0, ok == false

Warning: The QByteArray content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

This function ignores leading and trailing whitespace.

See also number().

float QByteArray::toFloat(bool *ok = nullptr) const

Returns the byte array converted to a float value.

Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

 QByteArray string("1234.56");
 bool ok;
 float a = string.toFloat(&ok);    // a == 1234.56, ok == true

 string = "1234.56 Volt";
 a = str.toFloat(&ok);              // a == 0, ok == false

Warning: The QByteArray content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

This function ignores leading and trailing whitespace.

See also number().

QByteArray QByteArray::toHex() const

Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and the letters a-f.

See also fromHex().

QByteArray QByteArray::toHex(char separator) const

This is an overloaded function.

Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and the letters a-f.

If separator is not '\0', the separator character is inserted between the hex bytes.

Example:

 QByteArray macAddress = QByteArray::fromHex("123456abcdef");
 macAddress.toHex(':'); // returns "12:34:56:ab:cd:ef"
 macAddress.toHex(0);   // returns "123456abcdef"

This function was introduced in Qt 5.9.

See also fromHex().

int QByteArray::toInt(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to an int using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

 QByteArray str("FF");
 bool ok;
 int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
 int dec = str.toInt(&ok, 10);     // dec == 0, ok == false

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

long QByteArray::toLong(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to a long int using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

 QByteArray str("FF");
 bool ok;
 long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
 long dec = str.toLong(&ok, 10);   // dec == 0, ok == false

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

This function was introduced in Qt 4.1.

See also number().

qlonglong QByteArray::toLongLong(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to a long long using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

QByteArray QByteArray::toLower() const

Returns a lowercase copy of the byte array. The bytearray is interpreted as a Latin-1 encoded string.

Example:

 QByteArray x("Qt by THE QT COMPANY");
 QByteArray y = x.toLower();
 // y == "qt by the qt company"

See also isLower(), toUpper(), and 8-bit Character Comparisons.

NSData *QByteArray::toNSData() const

Creates a NSData from a QByteArray. The NSData object is autoreleased.

This function was introduced in Qt 5.3.

See also fromNSData(), fromRawNSData(), fromRawData(), and toRawNSData().

QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude = QByteArray(), const QByteArray &include = QByteArray(), char percent = '%') const

Returns a URI/URL-style percent-encoded copy of this byte array. The percent parameter allows you to override the default '%' character for another.

By default, this function will encode all characters that are not one of the following:

ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"

To prevent characters from being encoded pass them to exclude. To force characters to be encoded pass them to include. The percent character is always encoded.

Example:

 QByteArray text = "{a fishy string?}";
 QByteArray ba = text.toPercentEncoding("{}", "s");
 qDebug(ba.constData());
 // prints "{a fi%73hy %73tring%3F}"

The hex encoding uses the numbers 0-9 and the uppercase letters A-F.

This function was introduced in Qt 4.4.

See also fromPercentEncoding() and QUrl::toPercentEncoding().

CFDataRef QByteArray::toRawCFData() const

Constructs a CFData that uses the bytes of the QByteArray.

The QByteArray's bytes are not copied.

The caller guarantees that the QByteArray will not be deleted or modified as long as this CFData object exists.

This function was introduced in Qt 5.3.

See also toCFData(), fromRawCFData(), fromCFData(), and fromRawData().

NSData *QByteArray::toRawNSData() const

Constructs a NSData that uses the bytes of the QByteArray.

The QByteArray's bytes are not copied.

The caller guarantees that the QByteArray will not be deleted or modified as long as this NSData object exists.

This function was introduced in Qt 5.3.

See also fromRawNSData(), fromNSData(), fromRawData(), and toNSData().

short QByteArray::toShort(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to a short using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

std::string QByteArray::toStdString() const

Returns a std::string object with the data contained in this QByteArray.

This operator is mostly useful to pass a QByteArray to a function that accepts a std::string object.

This function was introduced in Qt 5.4.

See also fromStdString() and QString::toStdString().

uint QByteArray::toUInt(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to an unsigned int using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

ulong QByteArray::toULong(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to an unsigned long int using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

This function was introduced in Qt 4.1.

See also number().

qulonglong QByteArray::toULongLong(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to an unsigned long long using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

ushort QByteArray::toUShort(bool *ok = nullptr, int base = 10) const

Returns the byte array converted to an unsigned short using base base, which is 10 by default and must be between 2 and 36, or 0.

If base is 0, the base is determined automatically using the following rules: If the byte array begins with "0x", it is assumed to be hexadecimal; if it begins with "0", it is assumed to be octal; otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Note: The conversion of the number is performed in the default C locale, irrespective of the user's locale.

See also number().

QByteArray QByteArray::toUpper() const

Returns an uppercase copy of the byte array. The bytearray is interpreted as a Latin-1 encoded string.

Example:

 QByteArray x("Qt by THE QT COMPANY");
 QByteArray y = x.toUpper();
 // y == "QT BY THE QT COMPANY"

See also isUpper(), toLower(), and 8-bit Character Comparisons.

QByteArray QByteArray::trimmed() const

Returns a byte array that has whitespace removed from the start and the end.

Whitespace means any character for which the standard C++ isspace() function returns true in the C locale. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

 QByteArray ba("  lots\t of\nwhitespace\r\n ");
 ba = ba.trimmed();
 // ba == "lots\t of\nwhitespace";

Unlike simplified(), trimmed() leaves internal whitespace alone.

See also simplified().

void QByteArray::truncate(int pos)

Truncates the byte array at index position pos.

If pos is beyond the end of the array, nothing happens.

Example:

 QByteArray ba("Stockholm");
 ba.truncate(5);             // ba == "Stock"

See also chop(), resize(), and left().

bool QByteArray::operator!=(const QString &str) const

Returns true if this byte array is not equal to string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

QByteArray &QByteArray::operator+=(const QByteArray &ba)

Appends the byte array ba onto the end of this byte array and returns a reference to this byte array.

Example:

 QByteArray x("free");
 QByteArray y("dom");
 x += y;
 // x == "freedom"

Note: QByteArray is an implicitly shared class. Consequently, if you append to an empty byte array, then the byte array will just share the data held in ba. In this case, no copying of data is done, taking constant time. If a shared instance is modified, it will be copied (copy-on-write), taking linear time.

If the byte array being appended to is not empty, a deep copy of the data is performed, taking linear time.

This operation typically does not suffer from allocation overhead, because QByteArray preallocates extra space at the end of the data so that it may grow without reallocating for each append operation.

See also append() and prepend().

QByteArray &QByteArray::operator+=(char ch)

This is an overloaded function.

Appends the character ch onto the end of this byte array and returns a reference to this byte array.

QByteArray &QByteArray::operator+=(const char *str)

This is an overloaded function.

Appends the string str onto the end of this byte array and returns a reference to this byte array.

bool QByteArray::operator<(const QString &str) const

Returns true if this byte array is lexically less than string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

bool QByteArray::operator<=(const QString &str) const

Returns true if this byte array is lexically less than or equal to string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

QByteArray &QByteArray::operator=(const char *str)

This is an overloaded function.

Assigns str to this byte array.

bool QByteArray::operator==(const QString &str) const

Returns true if this byte array is equal to string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

bool QByteArray::operator>(const QString &str) const

Returns true if this byte array is lexically greater than string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

bool QByteArray::operator>=(const QString &str) const

Returns true if this byte array is greater than or equal to string str; otherwise returns false.

The Unicode data is converted into 8-bit characters using QString::toUtf8().

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

QByteRef QByteArray::operator[](int i)

Returns the byte at index position i as a modifiable reference.

If an assignment is made beyond the end of the byte array, the array is extended with resize() before the assignment takes place.

Example:

 QByteArray ba("Hello, world");
 cout << ba[0]; // prints H
 ba[7] = 'W';
 // ba == "Hello, World"

The return value is of type QByteRef, a helper class for QByteArray. When you get an object of type QByteRef, you can use it as if it were a char &. If you assign to it, the assignment will apply to the character in the QByteArray from which you got the reference.

Note: Before Qt 5.14 it was possible to use this operator to access a character at an out-of-bounds position in the byte array, and then assign to such a position, causing the byte array to be automatically resized. Furthermore, assigning a value to the returned QByteRef would cause a detach of the byte array, even if the byte array has been copied in the meanwhile (and the QByteRef kept alive while the copy was taken). These behaviors are deprecated, and will be changed in a future version of Qt.

See also at().

char QByteArray::operator[](int i) const

This is an overloaded function.

Same as at(i).

char QByteArray::operator[](uint i) const

This is an overloaded function.

QByteRef QByteArray::operator[](uint i)

This is an overloaded function.

Related Non-Members

quint16 qChecksum(const char *data, uint len)

Returns the CRC-16 checksum of the first len bytes of data.

The checksum is independent of the byte order (endianness) and will be calculated accorded to the algorithm published in ISO 3309 (Qt::ChecksumIso3309).

Note: This function is a 16-bit cache conserving (16 entry table) implementation of the CRC-16-CCITT algorithm.

quint16 qChecksum(const char *data, uint len, Qt::ChecksumType standard)

Returns the CRC-16 checksum of the first len bytes of data.

The checksum is independent of the byte order (endianness) and will be calculated accorded to the algorithm published in standard.

Note: This function is a 16-bit cache conserving (16 entry table) implementation of the CRC-16-CCITT algorithm.

This function was introduced in Qt 5.9.

QByteArray qCompress(const QByteArray &data, int compressionLevel = -1)

Compresses the data byte array and returns the compressed data in a new byte array.

The compressionLevel parameter specifies how much compression should be used. Valid values are between 0 and 9, with 9 corresponding to the greatest compression (i.e. smaller compressed data) at the cost of using a slower algorithm. Smaller values (8, 7, ..., 1) provide successively less compression at slightly faster speeds. The value 0 corresponds to no compression at all. The default value is -1, which specifies zlib's default compression.

See also qUncompress().

QByteArray qCompress(const uchar *data, int nbytes, int compressionLevel = -1)

This is an overloaded function.

Compresses the first nbytes of data at compression level compressionLevel and returns the compressed data in a new byte array.

QByteArray qUncompress(const QByteArray &data)

Uncompresses the data byte array and returns a new byte array with the uncompressed data.

Returns an empty QByteArray if the input data was corrupt.

This function will uncompress data compressed with qCompress() from this and any earlier Qt version, back to Qt 3.1 when this feature was added.

Note: If you want to use this function to uncompress external data that was compressed using zlib, you first need to prepend a four byte header to the byte array containing the data. The header must contain the expected length (in bytes) of the uncompressed data, expressed as an unsigned, big-endian, 32-bit integer.

See also qCompress().

QByteArray qUncompress(const uchar *data, int nbytes)

This is an overloaded function.

Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data.

int qsnprintf(char *str, size_t n, const char *fmt, ...)

A portable snprintf() function, calls qvsnprintf.

fmt is the printf() format string. The result is put into str, which is a buffer of at least n bytes.

Warning: Call this function only when you know what you are doing since it shows different behavior on certain platforms. Use QString::asprintf() to format a string instead.

See also qvsnprintf() and QString::asprintf().

int qstrcmp(const char *str1, const char *str2)

A safe strcmp() function.

Compares str1 and str2. Returns a negative value if str1 is less than str2, 0 if str1 is equal to str2 or a positive value if str1 is greater than str2.

Special case 1: Returns 0 if str1 and str2 are both nullptr.

Special case 2: Returns an arbitrary non-zero value if str1 is nullptr or str2 is nullptr (but not both).

See also qstrncmp(), qstricmp(), qstrnicmp(), 8-bit Character Comparisons, and QByteArray::compare().

char *qstrcpy(char *dst, const char *src)

Copies all the characters up to and including the '\0' from src into dst and returns a pointer to dst. If src is nullptr, it immediately returns nullptr.

This function assumes that dst is large enough to hold the contents of src.

Note: If dst and src overlap, the behavior is undefined.

See also qstrncpy().

char *qstrdup(const char *src)

Returns a duplicate string.

Allocates space for a copy of src, copies it, and returns a pointer to the copy. If src is nullptr, it immediately returns nullptr.

Ownership is passed to the caller, so the returned string must be deleted using delete[].

int qstricmp(const char *str1, const char *str2)

A safe stricmp() function.

Compares str1 and str2 ignoring the case of the characters. The encoding of the strings is assumed to be Latin-1.

Returns a negative value if str1 is less than str2, 0 if str1 is equal to str2 or a positive value if str1 is greater than str2.

Special case 1: Returns 0 if str1 and str2 are both nullptr.

Special case 2: Returns a random non-zero value if str1 is nullptr or str2 is nullptr (but not both).

See also qstrcmp(), qstrncmp(), qstrnicmp(), 8-bit Character Comparisons, and QByteArray::compare().

uint qstrlen(const char *str)

A safe strlen() function.

Returns the number of characters that precede the terminating '\0', or 0 if str is nullptr.

See also qstrnlen().

int qstrncmp(const char *str1, const char *str2, uint len)

A safe strncmp() function.

Compares at most len bytes of str1 and str2.

Returns a negative value if str1 is less than str2, 0 if str1 is equal to str2 or a positive value if str1 is greater than str2.

Special case 1: Returns 0 if str1 and str2 are both nullptr.

Special case 2: Returns a random non-zero value if str1 is nullptr or str2 is nullptr (but not both).

See also qstrcmp(), qstricmp(), qstrnicmp(), 8-bit Character Comparisons, and QByteArray::compare().

char *qstrncpy(char *dst, const char *src, uint len)

A safe strncpy() function.

Copies at most len bytes from src (stopping at len or the terminating '\0' whichever comes first) into dst and returns a pointer to dst. Guarantees that dst is '\0'-terminated. If src or dst is nullptr, returns nullptr immediately.

This function assumes that dst is at least len characters long.

Note: If dst and src overlap, the behavior is undefined.

Note: When compiling with Visual C++ compiler version 14.00 (Visual C++ 2005) or later, internally the function strncpy_s will be used.

See also qstrcpy().

int qstrnicmp(const char *str1, const char *str2, uint len)

A safe strnicmp() function.

Compares at most len bytes of str1 and str2 ignoring the case of the characters. The encoding of the strings is assumed to be Latin-1.

Returns a negative value if str1 is less than str2, 0 if str1 is equal to str2 or a positive value if str1 is greater than str2.

Special case 1: Returns 0 if str1 and str2 are both nullptr.

Special case 2: Returns a random non-zero value if str1 is nullptr or str2 is nullptr (but not both).

See also qstrcmp(), qstrncmp(), qstricmp(), 8-bit Character Comparisons, and QByteArray::compare().

uint qstrnlen(const char *str, uint maxlen)

A safe strnlen() function.

Returns the number of characters that precede the terminating '\0', but at most maxlen. If str is nullptr, returns 0.

This function was introduced in Qt 4.2.

See also qstrlen().

int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap)

A portable vsnprintf() function. Will call ::vsnprintf(), ::_vsnprintf(), or ::vsnprintf_s depending on the system, or fall back to an internal version.

fmt is the printf() format string. The result is put into str, which is a buffer of at least n bytes.

The caller is responsible to call va_end() on ap.

Warning: Since vsnprintf() shows different behavior on certain platforms, you should not rely on the return value or on the fact that you will always get a 0 terminated string back.

Ideally, you should never call this function but use QString::asprintf() instead.

See also qsnprintf() and QString::asprintf().

bool operator!=(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is not equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator!=(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is not equal to string a2; otherwise returns false.

See also QByteArray::compare().

bool operator!=(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is not equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)

Returns a byte array that is the result of concatenating byte array a1 and byte array a2.

See also QByteArray::operator+=().

const QByteArray operator+(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating byte array a1 and string a2.

const QByteArray operator+(const QByteArray &a1, char a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating byte array a1 and character a2.

const QByteArray operator+(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating string a1 and byte array a2.

const QByteArray operator+(char a1, const QByteArray &a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating character a1 and byte array a2.

bool operator<(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is lexically less than byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator<(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is lexically less than string a2; otherwise returns false.

See also QByteArray::compare().

bool operator<(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is lexically less than byte array a2; otherwise returns false.

See also QByteArray::compare().

QDataStream &operator<<(QDataStream &out, const QByteArray &ba)

Writes byte array ba to the stream out and returns a reference to the stream.

See also Serializing Qt Data Types.

bool operator<=(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is lexically less than or equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator<=(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is lexically less than or equal to string a2; otherwise returns false.

See also QByteArray::compare().

bool operator<=(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is lexically less than or equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator==(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator==(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is equal to string a2; otherwise returns false.

See also QByteArray::compare().

bool operator==(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator>(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is lexically greater than byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator>(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is lexically greater than string a2; otherwise returns false.

See also QByteArray::compare().

bool operator>(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is lexically greater than byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator>=(const QByteArray &a1, const QByteArray &a2)

This is an overloaded function.

Returns true if byte array a1 is lexically greater than or equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

bool operator>=(const QByteArray &a1, const char *a2)

This is an overloaded function.

Returns true if byte array a1 is lexically greater than or equal to string a2; otherwise returns false.

See also QByteArray::compare().

bool operator>=(const char *a1, const QByteArray &a2)

This is an overloaded function.

Returns true if string a1 is lexically greater than or equal to byte array a2; otherwise returns false.

See also QByteArray::compare().

QDataStream &operator>>(QDataStream &in, QByteArray &ba)

Reads a byte array into ba from the stream in and returns a reference to the stream.

See also Serializing Qt Data Types.

Macro Documentation

QByteArrayLiteral(ba)

The macro generates the data for a QByteArray out of the string literal ba at compile time. Creating a QByteArray from it is free in this case, and the generated byte array data is stored in the read-only segment of the compiled object file.

For instance:

 QByteArray ba = QByteArrayLiteral("byte array contents");

Using QByteArrayLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QByteArray instances from data known at compile time.

See also QStringLiteral.

QT_NO_CAST_FROM_BYTEARRAY

Disables automatic conversions from QByteArray to const char * or const void *.

See also QT_NO_CAST_TO_ASCII and QT_NO_CAST_FROM_ASCII.