Qt 4.8
Classes | Public Types | Public Functions | Static Public Functions | Private Functions | Properties | Static Private Attributes | Friends | Related Functions | List of all members
QByteArray Class Reference

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

#include <qbytearray.h>

Classes

struct  Data
 

Public Types

typedef const char * const_iterator
 
typedef const char & const_reference
 
typedef const_iterator ConstIterator
 
typedef DataDataPtr
 
typedef char * iterator
 
typedef iterator Iterator
 
typedef char & reference
 
typedef char value_type
 

Public Functions

QByteArrayappend (char c)
 Appends the character ch to this byte array. More...
 
QByteArrayappend (const char *s)
 Appends the string str to this byte array. More...
 
QByteArrayappend (const char *s, int len)
 
QByteArrayappend (const QByteArray &a)
 Appends the byte array ba onto the end of this byte array. More...
 
QT_ASCII_CAST_WARN QByteArrayappend (const QString &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str to this byte array. More...
 
char at (int i) const
 Returns the character at index position i in the byte array. More...
 
iterator begin ()
 
const_iterator begin () const
 
int capacity () const
 Returns the maximum number of bytes that can be stored in the byte array without forcing a reallocation. More...
 
void chop (int n)
 Removes n bytes from the end of the byte array. More...
 
void clear ()
 Clears the contents of the byte array and makes it empty. More...
 
const_iterator constBegin () const
 
const char * constData () const
 Returns a pointer to the data stored in the byte array. More...
 
const_iterator constEnd () const
 
QBool contains (char c) const
 Returns true if the byte array contains the character ch; otherwise returns false. More...
 
QBool contains (const char *a) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns true if the byte array contains the string str; otherwise returns false. More...
 
QBool contains (const QByteArray &a) const
 Returns true if the byte array contains an occurrence of the byte array ba; otherwise returns false. More...
 
int count (char c) const
 Returns the number of occurrences of character ch in the byte array. More...
 
int count (const char *a) const
 Returns the number of (potentially overlapping) occurrences of string str in the byte array. More...
 
int count (const QByteArray &a) const
 Returns the number of (potentially overlapping) occurrences of byte array ba in this byte array. More...
 
int count () const
 Same as size(). More...
 
char * data ()
 Returns a pointer to the data stored in the byte array. More...
 
const char * data () const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
DataPtrdata_ptr ()
 
void detach ()
 
iterator end ()
 
const_iterator end () const
 
bool endsWith (const QByteArray &a) const
 Returns true if this byte array ends with byte array ba; otherwise returns false. More...
 
bool endsWith (char c) const
 Returns true if this byte array ends with character ch; otherwise returns false. More...
 
bool endsWith (const char *c) const
 Returns true if this byte array ends with string str; otherwise returns false. More...
 
QByteArrayfill (char c, int size=-1)
 Sets every byte in the byte array to character ch. More...
 
int indexOf (char c, int from=0) const
 Returns the index position of the first occurrence of the character ch in the byte array, searching forward from index position from. More...
 
int indexOf (const char *c, int from=0) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the index position of the first occurrence of the string str in the byte array, searching forward from index position from. More...
 
int indexOf (const QByteArray &a, 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. More...
 
QT_ASCII_CAST_WARN int indexOf (const QString &s, int from=0) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the index position of the first occurrence of the string str in the byte array, searching forward from index position from. More...
 
QByteArrayinsert (int i, char c)
 Inserts character ch at index position i in the byte array. More...
 
QByteArrayinsert (int i, const char *s)
 Inserts the string str at position i in the byte array. More...
 
QByteArrayinsert (int i, const char *s, int len)
 Inserts len bytes of the string str at position i in the byte array. More...
 
QByteArrayinsert (int i, const QByteArray &a)
 Inserts the byte array ba at index position i and returns a reference to this byte array. More...
 
QT_ASCII_CAST_WARN QByteArrayinsert (int i, const QString &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Inserts the string str at index position i in the byte array. More...
 
bool isDetached () const
 
bool isEmpty () const
 Returns true if the byte array has size 0; otherwise returns false. More...
 
bool isNull () const
 Returns true if this byte array is null; otherwise returns false. More...
 
bool isSharedWith (const QByteArray &other) const
 
int lastIndexOf (char c, int from=-1) const
 Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from. More...
 
int lastIndexOf (const char *c, int from=-1) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the index position of the last occurrence of the string str in the byte array, searching backward from index position from. More...
 
int lastIndexOf (const QByteArray &a, 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. More...
 
QT_ASCII_CAST_WARN int lastIndexOf (const QString &s, int from=-1) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the index position of the last occurrence of the string str in the byte array, searching backward from index position from. More...
 
QByteArray left (int len) const
 Returns a byte array that contains the leftmost len bytes of this byte array. More...
 
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. More...
 
int length () const
 Same as size(). More...
 
QByteArray mid (int index, int len=-1) const
 Returns a byte array containing len bytes from this byte array, starting at position pos. More...
 
 operator const char * () const
 
QT_ASCII_CAST_WARN bool operator!= (const QString &s2) const
 Returns true if this byte array is not equal to string str; otherwise returns false. More...
 
QByteArrayoperator+= (char c)
 Appends the character ch onto the end of this byte array and returns a reference to this byte array. More...
 
QByteArrayoperator+= (const char *s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str onto the end of this byte array and returns a reference to this byte array. More...
 
QByteArrayoperator+= (const QByteArray &a)
 Appends the byte array ba onto the end of this byte array and returns a reference to this byte array. More...
 
QT_ASCII_CAST_WARN QByteArrayoperator+= (const QString &s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str onto the end of this byte array and returns a reference to this byte array. More...
 
QT_ASCII_CAST_WARN bool operator< (const QString &s2) const
 Returns true if this byte array is lexically less than string str; otherwise returns false. More...
 
QT_ASCII_CAST_WARN bool operator<= (const QString &s2) const
 Returns true if this byte array is lexically less than or equal to string str; otherwise returns false. More...
 
QByteArrayoperator= (const QByteArray &)
 Assigns other to this byte array and returns a reference to this byte array. More...
 
QByteArrayoperator= (const char *str)
 Assigns str to this byte array. More...
 
QT_ASCII_CAST_WARN bool operator== (const QString &s2) const
 Returns true if this byte array is equal to string str; otherwise returns false. More...
 
QT_ASCII_CAST_WARN bool operator> (const QString &s2) const
 Returns true if this byte array is lexically greater than string str; otherwise returns false. More...
 
QT_ASCII_CAST_WARN bool operator>= (const QString &s2) const
 Returns true if this byte array is greater than or equal to string str; otherwise returns false. More...
 
char operator[] (int i) const
 Same as at(i). More...
 
char operator[] (uint i) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteRef operator[] (int i)
 Returns the byte at index position i as a modifiable reference. More...
 
QByteRef operator[] (uint i)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArrayprepend (char c)
 Prepends the character ch to this byte array. More...
 
QByteArrayprepend (const char *s)
 Prepends the string str to this byte array. More...
 
QByteArrayprepend (const char *s, int len)
 Prepends len bytes of the string str to this byte array. More...
 
QByteArrayprepend (const QByteArray &a)
 Prepends the byte array ba to this byte array and returns a reference to this byte array. More...
 
void push_back (char c)
 Same as append(ch). More...
 
void push_back (const char *c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Same as append(str). More...
 
void push_back (const QByteArray &a)
 This function is provided for STL compatibility. More...
 
void push_front (char c)
 Same as prepend(ch). More...
 
void push_front (const char *c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Same as prepend(str). More...
 
void push_front (const QByteArray &a)
 This function is provided for STL compatibility. More...
 
 QByteArray ()
 Constructs an empty byte array. More...
 
 QByteArray (const char *)
 Constructs a byte array initialized with the string str. More...
 
 QByteArray (const char *, int size)
 Constructs a byte array containing the first size bytes of array data. More...
 
 QByteArray (int size, char c)
 Constructs a byte array of size size with every byte set to character ch. More...
 
 QByteArray (int size, Qt::Initialization)
 Constructs a byte array of size size with uninitialized contents. More...
 
 QByteArray (const QByteArray &)
 Constructs a copy of other. More...
 
QByteArrayremove (int index, int len)
 Removes len bytes from the array, starting at index position pos, and returns a reference to the array. More...
 
QByteArray repeated (int times) const
 Returns a copy of this byte array repeated the specified number of times. More...
 
QByteArrayreplace (int index, int len, const char *s)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces len bytes from index position pos with the zero terminated string after. More...
 
QByteArrayreplace (int index, int len, const char *s, int alen)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces len bytes from index position pos with alen bytes from the string after. More...
 
QByteArrayreplace (int index, int len, const QByteArray &s)
 Replaces len bytes from index position pos with the byte array after, and returns a reference to this byte array. More...
 
QByteArrayreplace (char before, const char *after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the character before with the string after. More...
 
QByteArrayreplace (char before, const QByteArray &after)
 Replaces every occurrence of the character before with the byte array after. More...
 
QByteArrayreplace (const char *before, const char *after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the string after. More...
 
QByteArrayreplace (const char *before, int bsize, const char *after, int asize)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the string after. More...
 
QByteArrayreplace (const QByteArray &before, const QByteArray &after)
 Replaces every occurrence of the byte array before with the byte array after. More...
 
QByteArrayreplace (const QByteArray &before, const char *after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the byte array before with the string after. More...
 
QByteArrayreplace (const char *before, const QByteArray &after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the byte array after. More...
 
QByteArrayreplace (char before, char after)
 Replaces every occurrence of the character before with the character after. More...
 
QT_ASCII_CAST_WARN QByteArrayreplace (const QString &before, const char *after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the string after. More...
 
QT_ASCII_CAST_WARN QByteArrayreplace (char c, const QString &after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the character before with the string after. More...
 
QT_ASCII_CAST_WARN QByteArrayreplace (const QString &before, const QByteArray &after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the byte array after. More...
 
void reserve (int size)
 Attempts to allocate memory for at least size bytes. More...
 
void resize (int size)
 Sets the size of the byte array to size bytes. More...
 
QByteArray right (int len) const
 Returns a byte array that contains the rightmost len bytes of this byte array. More...
 
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. More...
 
QByteArraysetNum (short, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArraysetNum (ushort, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArraysetNum (int, 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. More...
 
QByteArraysetNum (uint, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArraysetNum (qlonglong, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArraysetNum (qulonglong, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
QByteArraysetNum (float, char f='g', int prec=6)
 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. More...
 
QByteArraysetNum (double, char f='g', int prec=6)
 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. More...
 
QByteArraysetRawData (const char *a, uint n)
 Resets the QByteArray to use the first size bytes of the data array. More...
 
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. More...
 
int size () const
 Returns the number of bytes in this byte array. More...
 
QList< QByteArraysplit (char sep) const
 Splits the byte array into subarrays wherever sep occurs, and returns the list of those arrays. More...
 
void squeeze ()
 Releases any memory not required to store the array's data. More...
 
bool startsWith (const QByteArray &a) const
 Returns true if this byte array starts with byte array ba; otherwise returns false. More...
 
bool startsWith (char c) const
 Returns true if this byte array starts with character ch; otherwise returns false. More...
 
bool startsWith (const char *c) const
 Returns true if this byte array starts with string str; otherwise returns false. More...
 
void swap (QByteArray &other)
 Swaps byte array other with this byte array. More...
 
QByteArray toBase64 () const
 Returns a copy of the byte array, encoded as Base64. More...
 
double toDouble (bool *ok=0) const
 Returns the byte array converted to a double value. More...
 
float toFloat (bool *ok=0) const
 Returns the byte array converted to a float value. More...
 
QByteArray toHex () const
 Returns a hex encoded copy of the byte array. More...
 
int toInt (bool *ok=0, 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. More...
 
long toLong (bool *ok=0, int base=10) const
 
qlonglong toLongLong (bool *ok=0, 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. More...
 
QByteArray toLower () const
 Returns a lowercase copy of the byte array. More...
 
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. More...
 
short toShort (bool *ok=0, 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. More...
 
uint toUInt (bool *ok=0, 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. More...
 
ulong toULong (bool *ok=0, int base=10) const
 
qulonglong toULongLong (bool *ok=0, 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. More...
 
QByteArray toUpper () const
 Returns an uppercase copy of the byte array. More...
 
ushort toUShort (bool *ok=0, 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. More...
 
QByteArray trimmed () const
 Returns a byte array that has whitespace removed from the start and the end. More...
 
void truncate (int pos)
 Truncates the byte array at index position pos. More...
 
 ~QByteArray ()
 Destroys the byte array. More...
 

Static Public Functions

static QByteArray fromBase64 (const QByteArray &base64)
 Returns a decoded copy of the Base64 array base64. More...
 
static QByteArray fromHex (const QByteArray &hexEncoded)
 Returns a decoded copy of the hex encoded array hexEncoded. More...
 
static QByteArray fromPercentEncoding (const QByteArray &pctEncoded, char percent='%')
 Returns a decoded copy of the URI/URL-style percent-encoded input. More...
 
static QByteArray fromRawData (const char *, int size)
 Constructs a QByteArray that uses the first size bytes of the data array. More...
 
static QByteArray number (int, int base=10)
 Returns a byte array containing the string equivalent of the number n to base base (10 by default). More...
 
static QByteArray number (uint, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static QByteArray number (qlonglong, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static QByteArray number (qulonglong, int base=10)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
static QByteArray number (double, char f='g', int prec=6)
 Returns a byte array that contains the printed value of n, formatted in format f with precision prec. More...
 

Private Functions

void expand (int i)
 
QByteArray nulTerminated () const
 Return a QByteArray that is sure to be NUL-terminated. More...
 
 operator QNoImplicitBoolCast () const
 
 QByteArray (Data *dd, int, int)
 
void realloc (int alloc)
 

Properties

Datad
 

Static Private Attributes

static Data shared_empty
 
static Data shared_null
 

Friends

class QByteRef
 
class QString
 
Q_CORE_EXPORT QByteArray qUncompress (const uchar *data, int nbytes)
 Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data. More...
 

Related Functions

(Note that these are not member functions.)

bool operator!= (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is not equal to byte array a2; otherwise returns false. More...
 
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)
 Returns a byte array that is the result of concatenating byte array a1 and byte array a2. More...
 
const QByteArray operator+ (const QByteArray &a1, const char *a2)
 
const QByteArray operator+ (const QByteArray &a1, char a2)
 Returns a byte array that is the result of concatenating byte array a1 and character a2. More...
 
const QByteArray operator+ (const char *a1, const QByteArray &a2)
 
const QByteArray operator+ (char a1, const QByteArray &a2)
 Returns a byte array that is the result of concatenating character a1 and byte array a2. More...
 
bool operator< (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is lexically less than byte array a2; otherwise returns false. More...
 
bool operator< (const QByteArray &a1, const char *a2)
 
bool operator< (const char *a1, const QByteArray &a2)
 
QDataStreamoperator<< (QDataStream &out, const QByteArray &ba)
 Writes byte array ba to the stream out and returns a reference to the stream. More...
 
bool operator<= (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is lexically less than or equal to byte array a2; otherwise returns false. More...
 
bool operator<= (const QByteArray &a1, const char *a2)
 
bool operator<= (const char *a1, const QByteArray &a2)
 
bool operator== (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is equal to byte array a2; otherwise returns false. More...
 
bool operator== (const QByteArray &a1, const char *a2)
 
bool operator== (const char *a1, const QByteArray &a2)
 
bool operator> (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is lexically greater than byte array a2; otherwise returns false. More...
 
bool operator> (const QByteArray &a1, const char *a2)
 
bool operator> (const char *a1, const QByteArray &a2)
 
bool operator>= (const QByteArray &a1, const QByteArray &a2)
 Returns true if byte array a1 is lexically greater than or equal to byte array a2; otherwise returns false. More...
 
bool operator>= (const QByteArray &a1, const char *a2)
 
bool operator>= (const char *a1, const QByteArray &a2)
 
QDataStreamoperator>> (QDataStream &in, QByteArray &ba)
 Reads a byte array into ba from the stream in and returns a reference to the stream. More...
 
quint16 qChecksum (const char *data, uint len)
 Returns the CRC-16 checksum of the first len bytes of data. More...
 
QByteArray qCompress (const QByteArray &data, int compressionLevel)
 Compresses the data byte array and returns the compressed data in a new byte array. More...
 
QByteArray qCompress (const uchar *data, int nbytes, int compressionLevel)
 Compresses the first nbytes of data and returns the compressed data in a new byte array. More...
 
int qsnprintf (char *str, size_t n, const char *fmt,...)
 A portable snprintf() function, calls qvsnprintf. More...
 
int qstrcmp (const char *str1, const char *str2)
 A safe strcmp() function. More...
 
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. More...
 
char * qstrdup (const char *src)
 Returns a duplicate string. More...
 
int qstricmp (const char *str1, const char *str2)
 A safe stricmp() function. More...
 
uint qstrlen (const char *str)
 
int qstrncmp (const char *str1, const char *str2, uint len)
 
char * qstrncpy (char *dst, const char *src, uint len)
 A safe strncpy() function. More...
 
int qstrnicmp (const char *str1, const char *str2, uint len)
 A safe strnicmp() function. More...
 
uint qstrnlen (const char *str, uint maxlen)
 
QByteArray qUncompress (const QByteArray &data)
 Uncompresses the data byte array and returns a new byte array with the uncompressed data. More...
 
int qvsnprintf (char *str, size_t n, const char *fmt, va_list ap)
 A portable vsnprintf() function. More...
 

Detailed Description

The QByteArray class provides an array of bytes.

Note
This class or function is reentrant.

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:

ba.resize(5);
ba[0] = 0x3c;

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

ba[3] = 0x18;
ba[4] = 0xca;

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

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

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

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

To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the data. The pointer is guaranteed to remain valid until a non-const function is called on the QByteArray. It is also guaranteed that the data ends with a '\0' byte 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:

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

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:

for (int i = 0; i < ba.size(); ++i) {
if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
cout << "Found character in range [a-f]" << endl;
}
QByteArray x("and");
x.prepend("rock "); // x == "rock and"
x.append(" roll"); // x == "rock and roll"
x.replace(5, 3, "&"); // x == "rock & roll"

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

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

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

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

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

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.

Definition at line 135 of file qbytearray.h.

Typedefs

◆ const_iterator

Warning
This function is not part of the public interface.

Definition at line 334 of file qbytearray.h.

◆ const_reference

Warning
This function is not part of the public interface.

Definition at line 345 of file qbytearray.h.

◆ ConstIterator

Warning
This function is not part of the public interface.

Definition at line 336 of file qbytearray.h.

◆ DataPtr

Warning
This function is not part of the public interface.

Definition at line 396 of file qbytearray.h.

◆ iterator

Warning
This function is not part of the public interface.

Definition at line 333 of file qbytearray.h.

◆ Iterator

Warning
This function is not part of the public interface.

Definition at line 335 of file qbytearray.h.

◆ reference

Warning
This function is not part of the public interface.

Definition at line 346 of file qbytearray.h.

◆ value_type

Warning
This function is not part of the public interface.

Definition at line 347 of file qbytearray.h.

Constructors and Destructors

◆ QByteArray() [1/7]

QByteArray::QByteArray ( )
inline

Constructs an empty byte array.

See also
isEmpty()

Definition at line 400 of file qbytearray.h.

Referenced by fromPercentEncoding(), fromRawData(), left(), mid(), operator+(), QByteArray(), repeated(), right(), toPercentEncoding(), and trimmed().

400 : d(&shared_null) { d->ref.ref(); }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
static Data shared_null
Definition: qbytearray.h:384

◆ QByteArray() [2/7]

QByteArray::QByteArray ( const char *  str)

Constructs a byte array initialized with the string str.

QByteArray makes a deep copy of the string data.

Definition at line 1401 of file qbytearray.cpp.

1402 {
1403  if (!str) {
1404  d = &shared_null;
1405  } else if (!*str) {
1406  d = &shared_empty;
1407  } else {
1408  int len = qstrlen(str);
1409  d = static_cast<Data *>(qMalloc(sizeof(Data)+len));
1410  Q_CHECK_PTR(d);
1411  d->ref = 0;;
1412  d->alloc = d->size = len;
1413  d->data = d->array;
1414  memcpy(d->array, str, len+1); // include null terminator
1415  }
1416  d->ref.ref();
1417 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
uint qstrlen(const char *str)
Definition: qbytearray.h:79
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ QByteArray() [3/7]

QByteArray::QByteArray ( const char *  data,
int  size 
)

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

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

QByteArray makes a deep copy of the string data.

See also
fromRawData()

Definition at line 1430 of file qbytearray.cpp.

1431 {
1432  if (!data) {
1433  d = &shared_null;
1434  } else if (size <= 0) {
1435  d = &shared_empty;
1436  } else {
1437  d = static_cast<Data *>(qMalloc(sizeof(Data) + size));
1438  Q_CHECK_PTR(d);
1439  d->ref = 0;
1440  d->alloc = d->size = size;
1441  d->data = d->array;
1442  memcpy(d->array, data, size);
1443  d->array[size] = '\0';
1444  }
1445  d->ref.ref();
1446 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ QByteArray() [4/7]

QByteArray::QByteArray ( int  size,
char  ch 
)

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

See also
fill()

Definition at line 1455 of file qbytearray.cpp.

1456 {
1457  if (size <= 0) {
1458  d = &shared_null;
1459  } else {
1460  d = static_cast<Data *>(qMalloc(sizeof(Data)+size));
1461  Q_CHECK_PTR(d);
1462  d->ref = 0;
1463  d->alloc = d->size = size;
1464  d->data = d->array;
1465  d->array[size] = '\0';
1466  memset(d->array, ch, size);
1467  }
1468  d->ref.ref();
1469 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
static Data shared_null
Definition: qbytearray.h:384

◆ QByteArray() [5/7]

QByteArray::QByteArray ( int  size,
Qt::Initialization   
)

Constructs a byte array of size size with uninitialized contents.

Warning
This function is not part of the public interface.

Definition at line 1480 of file qbytearray.cpp.

1481 {
1482  if (size <= 0) {
1483  d = &shared_empty;
1484  } else {
1485  d = static_cast<Data *>(qMalloc(sizeof(Data)+size));
1486  Q_CHECK_PTR(d);
1487  d->ref = 0;
1488  d->alloc = d->size = size;
1489  d->data = d->array;
1490  d->array[size] = '\0';
1491  }
1492  d->ref.ref();
1493 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
static Data shared_empty
Definition: qbytearray.h:385

◆ QByteArray() [6/7]

QByteArray::QByteArray ( const QByteArray other)
inline

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=()

Definition at line 439 of file qbytearray.h.

439  : d(a.d)
440 { d->ref.ref(); }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
long ASN1_INTEGER_get ASN1_INTEGER * a

◆ ~QByteArray()

QByteArray::~QByteArray ( )
inline

Destroys the byte array.

Definition at line 401 of file qbytearray.h.

401 { if (!d->ref.deref()) qFree(d); }
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139

◆ QByteArray() [7/7]

QByteArray::QByteArray ( Data dd,
int  ,
int   
)
inlineprivate

Definition at line 387 of file qbytearray.h.

387 : d(dd) {}
Data * d
Definition: qbytearray.h:386

Functions

◆ append() [1/5]

QByteArray & QByteArray::append ( char  ch)

Appends the character ch to this byte array.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1817 of file qbytearray.cpp.

Referenced by _q_dupEnvironment(), QFileSystemEngine::absoluteName(), QScript::QObjectConnectionManager::addSignalHandler(), QHttpNetworkReplyPrivate::appendCompressedReplyData(), QDeclarativeCompiler::buildDynamicMeta(), QUrlPrivate::canonicalHost(), QDeclarativeCompiler::compileAlias(), QDeclarativeListModelParser::compileProperty(), QDeclarativeObjectMethodScriptClass::connect(), QObject::connect(), ShaderEffectItem::connectPropertySignals(), QWindowsMimeURI::convertFromMime(), QDeclarativeObjectMethodScriptClass::disconnect(), QObject::disconnect(), QDeclarativeXMLHttpRequest::downloadProgress(), QDeclarativeCompiler::dumpStats(), QGLEngineSharedShaders::findProgramInCache(), QDeclarativeXMLHttpRequest::finished(), QGLPixmapConvolutionFilter::generateConvolutionShader(), generateGlyphTables(), QHttpNetworkReplyPrivate::getChunkSize(), QRegExpEngine::getEscape(), Maemo::getVariantFromDBusMessage(), QHttpNetworkReplyPrivate::gunzipBodyPartially(), QSslSocketBackendPrivate::initSslContext(), QMetaMethod::invoke(), QTextList::itemText(), QAxServerBase::Load(), QScriptEnginePrivate::newQObject(), QUrlPrivate::normalized(), QIBaseDriver::open(), operator+=(), QDeclarativeCompiledData::pack(), QDBusMetaObjectGenerator::parseMethods(), QDBusMetaObjectGenerator::parseSignals(), QWSDirectPainterSurface::permanentState(), QHttpNetworkConnectionChannel::pipelineInto(), prepend(), QPdfEnginePrivate::printString(), QDeclarativeBindingCompiler::program(), push_back(), qEncodeHmacMd5(), qEncodeLmv2Response(), qEncodeNtlmv2Response(), qGetBinaryData(), QGLEngineSharedShaders::QGLEngineSharedShaders(), QTest::qSignalDumperCallback(), qstring_to_xtp(), qt_socks5_set_host_address_and_port(), qt_socks5_set_host_name_and_port(), read_xpm_body(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), QPacketProtocolPrivate::readyToRead(), QAuthDevice::recvReadyRead(), QScript::QObjectConnectionManager::removeSignalHandler(), QOstDevicePrivate::RunL(), runlengthEncode(), QWinSettingsPrivate::set(), QDeclarativeParser::Object::setBindingBit(), QNetworkHeadersPrivate::setRawHeaderInternal(), QSslSocketBackendPrivate::startHandshake(), QTest::toString(), QLocalePrivate::validateChars(), Maemo::IAPConfPrivate::valueToVariant(), QWindowsPipeWriter::write(), and write_pbm_image().

1818 {
1819  if (d->ref != 1 || d->size + 1 > d->alloc)
1820  realloc(qAllocMore(d->size + 1, sizeof(Data)));
1821  d->data[d->size++] = ch;
1822  d->data[d->size] = '\0';
1823  return *this;
1824 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70

◆ append() [2/5]

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

Appends the string str to this byte array.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1767 of file qbytearray.cpp.

1768 {
1769  if (str) {
1770  int len = qstrlen(str);
1771  if (d->ref != 1 || d->size + len > d->alloc)
1772  realloc(qAllocMore(d->size + len, sizeof(Data)));
1773  memcpy(d->data + d->size, str, len + 1); // include null terminator
1774  d->size += len;
1775  }
1776  return *this;
1777 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ append() [3/5]

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

Definition at line 1794 of file qbytearray.cpp.

1795 {
1796  if (len < 0)
1797  len = qstrlen(str);
1798  if (str && len) {
1799  if (d->ref != 1 || d->size + len > d->alloc)
1800  realloc(qAllocMore(d->size + len, sizeof(Data)));
1801  memcpy(d->data + d->size, str, len); // include null terminator
1802  d->size += len;
1803  d->data[d->size] = '\0';
1804  }
1805  return *this;
1806 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ append() [4/5]

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 this is an empty QByteArray, then this 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 this is not an empty QByteArray, 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(), insert()

Definition at line 1729 of file qbytearray.cpp.

1730 {
1731  if ((d == &shared_null || d == &shared_empty) && !IS_RAW_DATA(ba.d)) {
1732  *this = ba;
1733  } else if (ba.d != &shared_null) {
1734  if (d->ref != 1 || d->size + ba.d->size > d->alloc)
1735  realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1736  memcpy(d->data + d->size, ba.d->data, ba.d->size);
1737  d->size += ba.d->size;
1738  d->data[d->size] = '\0';
1739  }
1740  return *this;
1741 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70
#define IS_RAW_DATA(d)
Definition: qbytearray.cpp:60
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ append() [5/5]

QByteArray & QByteArray::append ( const QString str)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str to this byte array.

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 996 of file qstring.h.

997 { return append(s.toAscii()); }
QByteArray & append(char c)
Appends the character ch to this byte array.

◆ at()

char QByteArray::at ( int  i) const
inline

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[]()

Definition at line 413 of file qbytearray.h.

Referenced by QFontDatabasePrivate::addQPF2File(), MetaObjectGenerator::addSetterSlot(), QSocks5PasswordAuthenticator::continueAuthenticate(), QWindowsMimeHtml::convertToMime(), QDBusArgumentPrivate::createSignature(), QODBCResult::exec(), QDeclarativeImportedNamespace::find_helper(), fromBase64(), fromHex(), QUrl::fromPunycode(), QXmlInputSource::fromRawData(), QXmlStreamReaderPrivate::getChar_helper(), QSettingsPrivate::iniEscapedString(), QWSDisplay::Data::init(), QSettingsPrivate::iniUnescapedKey(), QSettingsPrivate::iniUnescapedStringList(), QDeclarativeCompiler::isAttachedPropertyName(), QDeclarativeCompiler::isSignalPropertyName(), matchLineFeed(), QXlibMime::mimeConvertToFormat(), nextField(), nextNonWhitespace(), QUrlPrivate::normalized(), normalizeTypeInternal(), QSocks5SocketEnginePrivate::parseAuthenticationMethodReply(), QHttpNetworkReplyPrivate::parseHeader(), parseHeaderName(), parseHttpOptionHeader(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QHttpNetworkReplyPrivate::parseStatus(), QPictureIO::pictureFormat(), qax_generateDocumentation(), qDecodeDataUrl(), qHash(), qt_read_xpm_image_or_array(), read_xpm_string(), MetaObjectGenerator::readFuncsInfo(), QConfFileSettingsPrivate::readIniFile(), QConfFileSettingsPrivate::readIniLine(), QConfFileSettingsPrivate::readIniSection(), QPlatformFontDatabase::registerQPF2Font(), QUrl::resolved(), QUrl::setEncodedQueryItems(), QUrlPrivate::setEncodedUrl(), QWSDirectPainterSurface::setPermanentState(), QProcess::setReadChannel(), size(), QPatternist::HexBinary::stringValue(), QChar::toAscii(), toType(), QIntValidator::validate(), variantToString(), and QX11Data::xdndMimeConvertToFormat().

414 { Q_ASSERT(uint(i) < uint(size())); return d->data[i]; }
Data * d
Definition: qbytearray.h:386
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int uint
Definition: qglobal.h:996
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ begin() [1/2]

QByteArray::iterator QByteArray::begin ( )
inline
Warning
This function is not part of the public interface.

Definition at line 493 of file qbytearray.h.

Referenced by QDeclarativeComponentPrivate::beginCreate().

494 { detach(); return d->data; }
Data * d
Definition: qbytearray.h:386
void detach()
Definition: qbytearray.h:435

◆ begin() [2/2]

QByteArray::const_iterator QByteArray::begin ( ) const
inline
Warning
This function is not part of the public interface.

Definition at line 495 of file qbytearray.h.

496 { return d->data; }
Data * d
Definition: qbytearray.h:386

◆ capacity()

int QByteArray::capacity ( ) const
inline

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(), squeeze()

Definition at line 446 of file qbytearray.h.

447 { return d->alloc; }
Data * d
Definition: qbytearray.h:386

◆ chop()

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(), left()

Definition at line 1289 of file qbytearray.cpp.

Referenced by MetaObjectGenerator::addProperty(), qDecodeDataUrl(), qErrnoWarning(), QTest::qSignalDumperCallback(), qt_inflateGZipDataFrom(), QMimeDataPrivate::retrieveTypedData(), QSslCertificate::serialNumber(), and QUrlPrivate::toEncoded().

1290 {
1291  if (n > 0)
1292  resize(d->size - n);
1293 }
Data * d
Definition: qbytearray.h:386
void resize(int size)
Sets the size of the byte array to size bytes.

◆ clear()

void QByteArray::clear ( )

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

See also
resize(), isEmpty()

Definition at line 2907 of file qbytearray.cpp.

Referenced by QProgressDialogPrivate::_q_disconnectOnClose(), QSocks5SocketEnginePrivate::_q_emitPendingReadNotification(), QHttpPrivate::_q_slotReadyRead(), QPacketProtocolPrivate::aboutToClose(), QCryptographicHash::addData(), QHttpNetworkReplyPrivate::appendUncompressedReplyData(), QBitArray::clear(), QPacket::clear(), QUrlPrivate::clear(), QNetworkSessionPrivateImpl::clearConfiguration(), QFtpDTP::connectToHost(), QIcdEngine::doRequestUpdate(), QHttpNetworkReplyPrivate::eraseData(), QDeclarativeXMLHttpRequest::error(), QHttpNetworkReplyPrivate::findChallenge(), QGLEngineSharedShaders::findProgramInCache(), QDeclarativeXMLHttpRequest::finished(), QPSPrintEnginePrivate::flushPage(), QNetworkAccessFtpBackend::ftpReadyRead(), QXmlStreamReaderPrivate::getChar_helper(), QHttpNetworkReplyPrivate::getChunkSize(), QXmlStreamReaderPrivate::init(), QXlibMime::mimeAtomForFormat(), QTextStream::operator>>(), operator>>(), QUrlPrivate::parse(), QHttpNetworkConnectionChannel::pipelineFlush(), QPdf::ByteStream::prepareBuffer(), QGLEngineSharedShaders::QGLEngineSharedShaders(), QIODevice::read(), QByteDataBuffer::read(), QFtpDTP::readAll(), QIODevice::readAll(), QHttpNetworkReplyPrivate::readBodyFast(), MetaObjectGenerator::readFuncsInfo(), QHttpNetworkReplyPrivate::readHeader(), QIODevice::readLine(), QNetworkAccessFileBackend::readMoreFromFile(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkReplyPrivate::readStatus(), QPacketProtocolPrivate::readyToRead(), QNetworkAccessCache::removeEntry(), QNetworkAccessHttpBackend::replyDownloadData(), QCryptographicHash::reset(), runningUnderDebugger(), QUrlPrivate::setEncodedUserInfo(), QUrl::setFragment(), QUrl::setPassword(), QUrl::setPath(), QUrlPrivate::setUserInfo(), QUrl::setUserName(), QMetaType::unregisterType(), QLocalePrivate::validateChars(), and QX11Data::xdndMimeAtomForFormat().

2908 {
2909  if (!d->ref.deref())
2910  qFree(d);
2911  d = &shared_null;
2912  d->ref.ref();
2913 }
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139
static Data shared_null
Definition: qbytearray.h:384

◆ constBegin()

QByteArray::const_iterator QByteArray::constBegin ( ) const
inline
Warning
This function is not part of the public interface.

Definition at line 497 of file qbytearray.h.

498 { return d->data; }
Data * d
Definition: qbytearray.h:386

◆ constData()

const char * QByteArray::constData ( ) const
inline

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[](), fromRawData()

Definition at line 433 of file qbytearray.h.

Referenced by QAbstractSocketPrivate::_q_connectToNextAddress(), _q_dupEnvironment(), QWSServerPrivate::_q_newConnection(), QProcessPrivate::_q_notified(), QHttpPrivate::_q_slotConnected(), QHttpPrivate::_q_slotReadyRead(), QAbstractSocketPrivate::_q_startConnecting(), QSocks5SocketEnginePrivate::_q_udpSocketReadNotification(), QXmlTestLogger::addBenchmarkResult(), QTestLogger::addBenchmarkResult(), QGraphicsLayoutPrivate::addChildLayoutItem(), QPdfEnginePrivate::addConstantAlphaObject(), QAccessibleWidget::addControllingSignal(), QCryptographicHash::addData(), QNetworkAccessCache::addEntry(), QZipWriterPrivate::addEntry(), QPdfEnginePrivate::addImage(), QDnotifyFileSystemWatcherEngine::addPaths(), QFontDatabasePrivate::addQPF2File(), QGLShaderProgram::addShaderFromSourceCode(), QBasicUnixFontDatabase::addTTFile(), QFontDatabasePrivate::addTTFile(), QDeclarativeWatcher::addWatch(), QUrl::allEncodedQueryItemValues(), QUrl::allQueryItemValues(), QDBusMarshaller::append(), QString::append(), QHttpNetworkReplyPrivate::appendCompressedReplyData(), QDBusMarshaller::appendCrossMarshalling(), QNetworkReplyImplPrivate::appendDownstreamData(), QConcatenable< QByteArray >::appendTo(), QCoreApplication::applicationFilePath(), QTextHtmlParser::applyAttributes(), QMacStylePrivate::aquaSizeConstrain(), QPdf::ascii85Encode(), QWSSharedMemory::attach(), QSharedMemoryPrivate::attach(), QGLShaderProgram::attributeLocation(), QWaylandWindowManagerIntegration::authenticateWithToken(), QAudioDeviceInfoInternal::availableDevices(), QGLShaderProgram::bindAttributeLocation(), QDeclarativeCompiler::buildDynamicMeta(), QDeclarativeCompiler::buildPropertyOnAssignment(), buildString(), QDeclarativeCompiler::buildValueTypeProperty(), QTextCodec::canEncode(), QUrlPrivate::canonicalHost(), QPicturePrivate::checkFormat(), checksum(), childKeysOrGroups(), QFontEngineQPF::cleanUpAfterClientCrash(), QXlibClipboard::clipboardReadIncrementalProperty(), QX11Data::clipboardReadIncrementalProperty(), QPdfBaseEnginePrivate::closePrintDevice(), QDeclarativeListModelParser::compile(), QDeclarativeCompiler::compileAlias(), QGLShader::compileSourceCode(), QGLShader::compileSourceFile(), QVNCScreen::connect(), QMultiScreen::connect(), QTransformedScreen::connect(), QLinuxFbScreen::connect(), QDeclarativeObjectMethodScriptClass::connect(), QProxyScreen::connect(), QLinuxFbIntegration::connect(), QDirectFBScreen::connect(), QDBusConnection::connect(), QObject::connect(), ShaderEffectItem::connectPropertySignals(), QDBusConnectionPrivate::connectSignal(), QDBusConnection::connectToBus(), QAbstractSocket::connectToHost(), QAbstractSocket::connectToHostImplementation(), QWSSocket::connectToLocalFile(), QDBusConnection::connectToPeer(), QDeclarativeEnginePrivate::consoleLog(), QMacPasteboardMimeHTMLText::convertFromMime(), QWindowsMimeHtml::convertFromMime(), QMacPasteboardMimeVCard::convertFromMime(), QGb18030Codec::convertFromUnicode(), QBig5Codec::convertFromUnicode(), QUtf8::convertFromUnicode(), QSimpleTextCodec::convertFromUnicode(), QBig5hkscsCodec::convertFromUnicode(), QGbkCodec::convertFromUnicode(), QEucKrCodec::convertFromUnicode(), QEucJpCodec::convertFromUnicode(), QSjisCodec::convertFromUnicode(), QGb2312Codec::convertFromUnicode(), QTsciiCodec::convertFromUnicode(), QCP949Codec::convertFromUnicode(), QMacPasteboardMime::convertor(), QAbstractConcatenable::convertToAscii(), QMacPasteboardMimePlainText::convertToMime(), QMacPasteboardMimeUnicodeText::convertToMime(), QWindowsMimeURI::convertToMime(), QMacPasteboardMimeTiff::convertToMime(), QIconvCodec::convertToUnicode(), convertTypes(), QScriptEnginePrivate::convertValue(), QBitArray::count(), QWSSharedMemory::create(), QSharedMemoryPrivate::create(), QDeclarativeBinding::createBinding(), QUrlPrivate::createErrorString(), QDBusArgumentPrivate::createSignature(), QBBRootWindow::createWindowGroup(), QFileSystemEngine::currentPath(), data(), QSslKeyPrivate::decodePem(), QTest::defaultKeyVerbose(), QScript::QMetaObjectWrapperObject::deleteProperty(), QWSSharedMemory::detach(), QSharedMemoryPrivate::detach(), QDeclarativeObjectMethodScriptClass::disconnect(), QObject::disconnect(), QDBusConnectionPrivate::disconnectSignal(), QNetworkSessionPrivateImpl::do_open(), QPainter::drawText(), QPdfEnginePrivate::drawTextItem(), QDeclarativeBindingCompiler::dump(), ModelNode::dump(), QGraphicsAnchorLayoutPrivate::dumpGraph(), QDeclarativeCompiler::dumpStats(), QUrl::encodedQueryItems(), QUrl::encodedQueryItemValue(), QPicturePaintEngine::end(), QtopiaPrintEngine::end(), QApplicationPrivate::enterModal_sys(), QWSClient::errorHandler(), QDeclarativeCompiler::evaluateEnum(), QXmlQuery::evaluateTo(), QDB2Result::exec(), QSQLiteResult::exec(), QSymSQLResult::exec(), QSqlQuery::exec(), QODBCResult::exec(), QPSQLDriverPrivate::exec(), QOCICols::execBatch(), QScript::QObjectConnectionManager::execute(), QAbstractSocketPrivate::fetchConnectionParameters(), QNativeSocketEnginePrivate::fetchConnectionParameters(), QZipReader::fileData(), QBitArray::fill(), QFileSystemEngine::fillMetaData(), QTextStreamPrivate::fillReadBuffer(), findEncoding(), QNetworkHeadersPrivate::findRawHeader(), QDeclarativePropertyPrivate::findSignalByName(), QIntValidator::fixup(), QMacPasteboardMime::flavorToMime(), QMinimalWindowSurface::flush(), QTextStreamPrivate::flushWriteBuffer(), fontExists(), QDropEvent::format(), QTest::formatResult(), QBBClipboard::MimeData::formats(), QImage::fromData(), QDirectFBPixmapData::fromFile(), QDirectFbBlitterPlatformPixmap::fromFile(), QGLPixmapData::fromFile(), fromHex(), QNetworkHeadersPrivate::fromHttpDate(), QString::fromLatin1(), QHostInfo::fromName(), QHostInfoAgent::fromName(), QHostInfoPrivate::fromName(), fromPercentEncodingHelper(), fromPercentEncodingMutable(), QUrl::fromPunycode(), QXmlInputSource::fromRawData(), QMetaObjectBuilder::fromRelocatableData(), QUuid::fromRfc4122(), QDeclarativeCompiler::genObject(), get_named_rgb(), get_network_interface(), QXmlStreamReaderPrivate::getChar_helper(), QFreetypeFace::getFace(), getFamiliesAndSignatures(), getNetWmState(), QScript::QObjectDelegate::getOwnPropertyDescriptor(), QScript::QMetaObjectWrapperObject::getOwnPropertyDescriptor(), QScript::QObjectDelegate::getOwnPropertySlot(), QScript::QMetaObjectWrapperObject::getOwnPropertySlot(), QBBGLContext::getProcAddress(), QWSPropertyManager::getProperty(), QFileIconProviderPrivate::getWinIcon(), QApplicationPrivate::globalEventProcessor(), QFontEngine::glyphCount(), QSystemSemaphorePrivate::handle(), QUrl::hasEncodedQueryItem(), QBBClipboard::MimeData::hasFormat(), QNonContiguousByteDeviceThreadForwardImpl::haveDataSlot(), QHttpNetworkHeaderPrivate::headerFieldValues(), QDeclarativeImportDatabase::importPlugin(), QXmlStreamWriterPrivate::indent(), QByteArrayMatcher::indexIn(), QDeclarativeCompiler::indexOfProperty(), QTestFileLogger::init(), QWSDisplay::Data::init(), QAuServerNAS::init(), QWSServerSocket::init(), init_platform(), QSignalSpy::initArgs(), QImageReaderPrivate::initHandler(), QNativeSocketEngine::initialize(), initializeDb(), QDirectFbIntegration::initializeDirectFB(), QAxBase::initializeLicensedHelper(), QDeclarativePropertyPrivate::initProperty(), QAbstractSocketPrivate::initSocketLayer(), QSslSocketBackendPrivate::initSslContext(), QSettingsPrivate::iniUnescapedStringList(), QDeclarativeJS::integerFromString(), QScript::integerFromString(), QSqlDatabasePrivate::invalidateDb(), QMetaMethod::invoke(), QAxServerBase::Invoke(), QMetaObject::invokeMethod(), QHttpNetworkReplyPrivate::isGzipped(), QDeclarativeMetaType::isModule(), QDBusUtil::isValidSignature(), QDBusUtil::isValidSingleSignature(), QMetaEnum::keysToValue(), launch(), launchWebBrowser(), QApplicationPrivate::leaveModal_sys(), QTcpServer::listen(), QSvgIOHandlerPrivate::load(), QResourcePrivate::load(), QFontDatabasePrivate::loadFromCache(), QPixmap::loadFromData(), QImage::loadFromData(), QFontEngine::loadKerningPairs(), loadSingleEngine(), ShaderEffectItem::lookThroughShaderCode(), QHostInfo::lookupHost(), QPatternist::XQueryTokenizer::lookupKeyword(), QScriptStdMessageHandler::message(), QXlibMime::mimeConvertToFormat(), QXlibMime::mimeStringToAtom(), multicastMembershipHelper(), nameMatch(), QNativeSocketEnginePrivate::nativeBind(), QNativeSocketEnginePrivate::nativeConnect(), QNativeSocketEnginePrivate::nativeListen(), QFSFileEnginePrivate::nativeOpen(), QNativeSocketEnginePrivate::nativeReceiveDatagram(), QBBNativeInterface::nativeResourceForWidget(), QNativeSocketEnginePrivate::nativeSendDatagram(), QMetaObject::newInstance(), QUrlPrivate::normalized(), QIBaseDriver::open(), QSQLiteDriver::open(), QAudioDeviceInfoInternal::open(), QTDSDriver::open(), QMYSQLDriver::open(), QAudioInputPrivate::open(), QPSQLDriver::open(), QWSTslibMouseHandlerPrivate::open(), QAudioOutputPrivate::open(), QWSPcMouseHandlerPrivate::openDevices(), QLinuxFbIntegrationPrivate::openTty(), QLinuxFbScreenPrivate::openTty(), PvrEglScreen::openTty(), QString::operator!=(), operator+(), QString::operator+=(), QString::operator<(), QDeclarativeInfo::operator<<(), QTextStream::operator<<(), operator<<(), QString::operator<=(), QString::operator=(), QString::operator==(), operator==(), QString::operator>(), QString::operator>=(), QUuid::operator>>(), QBitArray::operator^=(), QBitArray::operator|=(), QBitArray::operator~(), QDeclarativeCompiledData::pack(), QDateTimeParser::parse(), QUrlPrivate::parse(), parseDateString(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), QDateTimeParser::parseFormat(), parseHeaderName(), parseHttpOptionHeader(), QDeclarativeBindingCompilerPrivate::parseName(), QBBNavigatorEventNotifier::parsePPS(), QBBButtonEventNotifier::parsePPS(), QHttpNetworkReplyPrivate::parseStatus(), QPdf::patternForBrush(), QBufferPrivate::peek(), QIODevicePrivate::peek(), QRingBuffer< T >::peek(), QAuServerNAS::play(), QIBaseResult::prepare(), QSqlQuery::prepare(), QString::prepend(), printHelp(), QFtpPI::processReply(), QDeclarativeBindingCompiler::program(), QMacPasteboard::promiseKeeper(), QScript::QMetaObjectWrapperObject::put(), QTextStreamPrivate::putString(), q_toPercentEncoding(), qax_generateDocumentation(), QByteArrayMatcher::QByteArrayMatcher(), QTest::qCompare(), qCompress(), QDBusError::QDBusError(), QDBusServer::QDBusServer(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), qDecodeOCIType(), qEncodeNtlmv2Response(), qErrnoWarning(), QTest::qExec(), qExtractSecurityPolicyFromString(), QFontEngineQPF::QFontEngineQPF(), qGetBinaryData(), qHash(), QLinuxInputKeyboardHandler::QLinuxInputKeyboardHandler(), QLinuxInputMouseHandler::QLinuxInputMouseHandler(), QLock::QLock(), qMetaTypeCustomType_unlocked(), qmlRegisterCustomType(), qmlRegisterExtendedType(), qmlRegisterInterface(), qmlRegisterRevision(), qmlRegisterType(), qmlRegisterUncreatableType(), QDeclarativePrivate::qmlRegisterUncreatableType(), qmlRegisterValueTypeEnums(), QNonContiguousByteDeviceBufferImpl::QNonContiguousByteDeviceBufferImpl(), qOraOutValue(), qParseOpts(), QTest::qPrintMessage(), QQnxMouseHandler::QQnxMouseHandler(), QTest::qSignalDumperCallback(), QSignalSpy::QSignalSpy(), qSqlWarning(), qstrcmp(), qStreamNtlmBuffer(), qstring_to_xtp(), qStringFromUcs2Le(), qt_addPatternProps(), qt_adopted_thread_watcher_function(), qt_create_commandline(), qt_fill_input_buffer(), qt_get_screen(), qt_initIcu(), QApplicationPrivate::qt_mac_apply_settings(), qt_mac_create_fsref(), qt_mac_display_change_callbk(), qt_mac_execute_apple_script(), qt_message(), qt_nograb(), qt_parse_pattern(), qt_socks5_get_host_address_and_port(), qt_tildeExpansion(), qt_u_strToCase(), qt_x11_set_fallback_font_family(), QTDSResult::QTDSResult(), QTsLibMouseHandler::QTsLibMouseHandler(), queryFont(), QUrl::queryItems(), QDeclarativeValueTypeScriptClass::queryProperty(), QDeclarativeTypeNameScriptClass::queryProperty(), queuedConnectionTypes(), qUncompress(), QUuid::QUuid(), QVariantToVARIANT(), QVFbKeyboardHandler::QVFbKeyboardHandler(), QVFbMouseHandler::QVFbMouseHandler(), QVFbScreenKeyboardHandler::QVFbScreenKeyboardHandler(), QVFbScreenMouseHandler::QVFbScreenMouseHandler(), qvsnprintf(), QWaylandSelection::QWaylandSelection(), qws_dataDir(), QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(), QWSLinuxInputMousePrivate::QWSLinuxInputMousePrivate(), QWSLinuxTPMouseHandlerPrivate::QWSLinuxTPMouseHandlerPrivate(), QWSQnxKeyboardHandler::QWSQnxKeyboardHandler(), QWSTtyKbPrivate::QWSTtyKbPrivate(), QXcbConnection::QXcbConnection(), QXIMInputContext::QXIMInputContext(), QAudioInputPrivate::read(), QByteDataBuffer::read(), read_xpm_body(), QHttpMultiPartIODevice::readData(), QAuthDevice::readData(), QSocks5SocketEngine::readDatagram(), QConfFileSettingsPrivate::readIniFile(), QWinSettingsPrivate::readKey(), QRingBuffer< T >::readPointer(), QNonContiguousByteDeviceByteArrayImpl::readPointer(), QRingBuffer< T >::readPointerAtPosition(), QMYSQLDriver::record(), QAuthDevice::recvReadyRead(), registerComponent(), QDeclarativeEnginePrivate::registerCompositeType(), registerFont(), QPlatformFontDatabase::registerQPF2Font(), QStateMachinePrivate::registerSignalTransition(), QWSDisplay::Data::reinit(), QDBusConnectionPrivate::relaySignal(), QNetworkAccessCache::releaseEntry(), releaseFontData(), QUrl::removeAllEncodedQueryItems(), QHttpNetworkReplyPrivate::removeAutoDecompressHeader(), removeDotsFromPath(), QUrl::removeEncodedQueryItem(), QNetworkAccessCache::removeEntry(), QGraphicsLayoutPrivate::reparentChildItems(), replace(), QBBNavigatorEventNotifier::replyPPS(), QSQLite2Result::reset(), QTDSResult::reset(), QUrl::resolved(), resolveGdi32(), QDeclarativePropertyPrivate::restore(), QWaylandClipboard::retrieveData(), QBBClipboard::MimeData::retrieveData(), QKqueueFileSystemWatcherEngine::run(), QDeclarativeVME::run(), runlengthEncode(), QAxServerBase::Save(), QToolBarAreaLayout::saveState(), QWSServerPrivate::sendFontRemovedEvent(), QKeyMapper::sendKeyEvent(), QWSServerPrivate::sendQCopEvent(), QWinSettingsPrivate::set(), set_text(), QColor::setColorFromString(), QNetworkHeadersPrivate::setCookedHeader(), QTimeLinePrivate::setCurrentTime(), QDeclarativeListModelParser::setCustomData(), QWizard::setField(), QPainter::setFont(), QWSFontCommand::setFontName(), QHttpNetworkHeaderPrivate::setHeaderField(), setOptionFlag(), QByteArrayMatcher::setPattern(), QDirectFBWindowSurface::setPermanentState(), QWSLocalMemSurface::setPermanentState(), QWSSharedMemSurface::setPermanentState(), QWSOnScreenSurface::setPermanentState(), QWSYellowSurface::setPermanentState(), QPrinter::setPrinterName(), QWSDisplay::setProperty(), QNetworkHeadersPrivate::setRawHeaderInternal(), QTextBrowserPrivate::setSource(), QDeclarativeOpenMetaObject::setValue(), QWidgetPrivate::setWindowRole(), QXcbWindow::setWindowTitle(), QXlibWindow::setWindowTitle(), QWidgetPrivate::setWindowTitle_sys(), QBitArray::size(), sm_setProperty(), QFtpDTP::socketReadyRead(), QProcessPrivate::startDetached(), QProcessPrivate::startProcess(), QFontEngineMac::stringToCMap(), QFontEngineXLFD::stringToCMap(), QPatternist::Base64Binary::stringValue(), QIBaseDriver::subscribeToNotificationImplementation(), QDeclarativeCompiler::testQualifiedEnumAssignment(), QAudioDeviceInfoInternal::testSettings(), QSingleShotTimer::timerEvent(), toDouble(), toLongLong(), QUrl::toPercentEncoding(), toPercentEncoding(), QString::toStdString(), QTest::toString(), toULongLong(), QTextCodec::toUnicode(), QTextDecoder::toUnicode(), translateWSAError(), QMetaType::typeName(), QGLShaderProgram::uniformLocation(), ShaderEffectItem::updateEffectState(), QPropertyAnimationPrivate::updateMetaProperty(), QGLContext::updatePaintDevice(), QPropertyAnimationPrivate::updateProperty(), QIntValidator::validate(), QDoubleValidatorPrivate::validateWithLocale(), QSettingsPrivate::variantToString(), Maemo::IAPConfPrivate::variantToValue(), QMYSQLResult::virtual_hook(), QBBScreen::windowGroupName(), WinMain(), QIODevice::write(), QPdfEnginePrivate::write(), QRfbRawEncoder::write(), QRfbHextileEncoder< SRC >::write(), QUnixSocketPrivate::writeActivated(), QPdfEnginePrivate::writeCompressed(), QUdpSocket::writeDatagram(), writeProperty(), QX11Data::xdndMimeConvertToFormat(), QX11Data::xdndMimeStringToAtom(), xic_draw_callback(), and QLock::~QLock().

434 { return d->data; }
Data * d
Definition: qbytearray.h:386

◆ constEnd()

QByteArray::const_iterator QByteArray::constEnd ( ) const
inline
Warning
This function is not part of the public interface.

Definition at line 503 of file qbytearray.h.

504 { return d->data + d->size; }
Data * d
Definition: qbytearray.h:386

◆ contains() [1/3]

QBool QByteArray::contains ( char  ch) const
inline

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 525 of file qbytearray.h.

Referenced by addDefaultArguments(), buildSpec(), QAuthenticatorPrivate::calculateResponse(), QSvgIOHandler::canRead(), QByteDataBuffer::canReadLine(), QHttpNetworkConnectionChannel::detectPipeliningSupport(), fontFile(), QScript::QObjectDelegate::getOwnPropertyDescriptor(), QScript::QObjectDelegate::getOwnPropertySlot(), initializeDb(), QUrlPrivate::mergePaths(), QUrlPrivate::normalized(), QBBButtonEventNotifier::parsePPS(), QScript::QObjectDelegate::put(), qDetectCPUFeatures(), QPictureHandler::QPictureHandler(), qt_init(), read_xbm_body(), MetaObjectGenerator::readFuncsInfo(), QHttpNetworkReplyPrivate::readHeader(), setupLocaleMapper(), and QNetworkCookie::toRawForm().

526 { return QBool(indexOf(c) != -1); }
unsigned char c[8]
Definition: qnumeric_p.h:62
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...

◆ contains() [2/3]

QBool QByteArray::contains ( const char *  a) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns true if the byte array contains the string str; otherwise returns false.

Definition at line 575 of file qbytearray.h.

576 { return QBool(indexOf(c) != -1); }
unsigned char c[8]
Definition: qnumeric_p.h:62
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...

◆ contains() [3/3]

QBool QByteArray::contains ( const QByteArray ba) const
inline

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

See also
indexOf(), count()

Definition at line 523 of file qbytearray.h.

524 { return QBool(indexOf(a) != -1); }
long ASN1_INTEGER_get ASN1_INTEGER * a
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...

◆ count() [1/4]

int QByteArray::count ( char  ch) const

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
contains(), indexOf()

Definition at line 2654 of file qbytearray.cpp.

Referenced by QFontDatabasePrivate::addQPF2File(), QXmlStreamWriterPrivate::checkIfASCIICompatibleCodec(), QDeclarativeListModelParser::compile(), QDeclarativeListModelParser::compileProperty(), QHttpNetworkReplyPrivate::parseHeader(), QNetworkAccessManagerPrivate::prepareMultipart(), QDeclarativeBindingCompiler::program(), q_fromPercentEncoding(), q_toPercentEncoding(), QHttpMultiPartPrivate::QHttpMultiPartPrivate(), QVariantToVARIANT(), QHttpMultiPartIODevice::readData(), QPlatformFontDatabase::registerQPF2Font(), QPatternist::HexBinary::stringValue(), and variantToString().

2655 {
2656  int num = 0;
2657  const char *i = d->data + d->size;
2658  const char *b = d->data;
2659  while (i != b)
2660  if (*--i == ch)
2661  ++num;
2662  return num;
2663 }
Data * d
Definition: qbytearray.h:386

◆ count() [2/4]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2637 of file qbytearray.cpp.

2638 {
2639  return count(fromRawData(str, qstrlen(str)));
2640 }
int count() const
Same as size().
Definition: qbytearray.h:355
static QByteArray fromRawData(const char *, int size)
Constructs a QByteArray that uses the first size bytes of the data array.
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ count() [3/4]

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(), indexOf()

Definition at line 2612 of file qbytearray.cpp.

2613 {
2614  int num = 0;
2615  int i = -1;
2616  if (d->size > 500 && ba.d->size > 5) {
2617  QByteArrayMatcher matcher(ba);
2618  while ((i = matcher.indexIn(*this, i + 1)) != -1)
2619  ++num;
2620  } else {
2621  while ((i = indexOf(ba, i + 1)) != -1)
2622  ++num;
2623  }
2624  return num;
2625 }
Data * d
Definition: qbytearray.h:386
The QByteArrayMatcher class holds a sequence of bytes that can be quickly matched in a byte array...
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...

◆ count() [4/4]

int QByteArray::count ( ) const
inline

Same as size().

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 355 of file qbytearray.h.

Referenced by QDeclarativeComponentPrivate::beginCreate(), count(), and QDeclarativeComponent::QDeclarativeComponent().

355 { return d->size; }
Data * d
Definition: qbytearray.h:386

◆ data() [1/2]

char * QByteArray::data ( )
inline

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 << "]" << 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";
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(), operator[]()

Definition at line 429 of file qbytearray.h.

Referenced by QProcessPrivate::_q_notified(), QHttpPrivate::_q_slotReadyRead(), QAxClientSite::activateObject(), QTestLogger::addBenchmarkResult(), QLayout::addChildLayout(), QLayout::addChildWidget(), QIcdEngine::addConfiguration(), QSqlDatabasePrivate::addDatabase(), QZipWriterPrivate::addEntry(), QPdfEnginePrivate::addImage(), MetaObjectGenerator::addProperty(), QResource::addSearchPath(), QGridLayout::addWidget(), Maemo::appendVariantToDBusMessage(), QApplicationPrivate::applyX11SpecificCommandLineArguments(), QString::arg(), QPdf::ascii85Encode(), QPatternist::Base64Binary::base64Decode(), QSocks5PasswordAuthenticator::beginAuthenticate(), bindFont(), QOCIResultPrivate::bindValue(), QDeclarativeCompiler::buildDynamicMeta(), QDeclarativeBindingCompilerPrivate::buildExceptionData(), QFileSystemEngine::canonicalName(), QSslCertificatePrivate::certificatesFromDer(), QSslCertificatePrivate::certificatesFromPem(), checkHRESULT(), QCoreApplicationPrivate::checkReceiverThread(), checkSymbolFont(), checkWidget(), childKeysOrGroups(), QGLContext::choosePixelFormat(), QXlibClipboard::clipboardReadIncrementalProperty(), QX11Data::clipboardReadIncrementalProperty(), QXlibClipboard::clipboardReadProperty(), QX11Data::clipboardReadProperty(), QDeclarativeListModelParser::compile(), compressHelper(), QVFbScreen::connect(), QUnixSocket::connect(), QMetaObject::connectSlotsByName(), convertFlags(), QWindowsMimeText::convertFromMime(), QWindowsMimeURI::convertFromMime(), QMacPasteboardMimeTiff::convertFromMime(), QWindowsMimeHtml::convertFromMime(), QBuiltInMimes::convertFromMime(), QFontJis0201Codec::convertFromUnicode(), QGb18030Codec::convertFromUnicode(), QBig5Codec::convertFromUnicode(), QLatin1Codec::convertFromUnicode(), QUtf8::convertFromUnicode(), QFontLaoCodec::convertFromUnicode(), QIsciiCodec::convertFromUnicode(), QSimpleTextCodec::convertFromUnicode(), QUtf16::convertFromUnicode(), QIconvCodec::convertFromUnicode(), QBig5hkscsCodec::convertFromUnicode(), QUtf32::convertFromUnicode(), QGbkCodec::convertFromUnicode(), QLatin15Codec::convertFromUnicode(), QFontJis0208Codec::convertFromUnicode(), QEucKrCodec::convertFromUnicode(), QEucJpCodec::convertFromUnicode(), QSjisCodec::convertFromUnicode(), QGb2312Codec::convertFromUnicode(), QTsciiCodec::convertFromUnicode(), QFontBig5Codec::convertFromUnicode(), QCP949Codec::convertFromUnicode(), QFontGb2312Codec::convertFromUnicode(), QFontBig5hkscsCodec::convertFromUnicode(), QFontKsc5601Codec::convertFromUnicode(), QFontGbkCodec::convertFromUnicode(), QFontGb18030_0Codec::convertFromUnicode(), QWindowsLocalCodec::convertFromUnicode(), QWindowsMimeText::convertToMime(), QWindowsMimeURI::convertToMime(), QBuiltInMimes::convertToMime(), QIconvCodec::convertToUnicode(), QBitArray::count(), create_wm_client_leader(), QLayoutPrivate::createSpacerItem(), decodeMSG(), QSslKeyPrivate::decodePem(), deleteChildGroups(), QIcdEngine::deleteConfiguration(), QNetworkSessionPrivateImpl::do_open(), QIcdEngine::doRequestUpdate(), QRasterPaintEngine::drawTextItem(), dumpRecursive(), QClipboardWatcher::empty(), err_info_about_objects(), QFontEngineMac::faceId(), QFontconfigDatabase::fallbacksForFamily(), QXmlSimpleReader::feature(), QWSSoundServerPrivate::feedDevice(), QIBaseResultPrivate::fetchArray(), QIBaseResultPrivate::fetchBlob(), QXmlInputSource::fetchData(), QZipReader::fileData(), QBitArray::fill(), QFontconfigDatabase::fontEngine(), QXlibClipboardMime::formats_sys(), QMYSQLDriver::formatValue(), QAudioOutputPrivate::freeBlocks(), fromHex(), fromPercentEncoding(), fromRawData(), QFont::fromString(), QXmlStreamReaderPrivate::getChar_helper(), QXlibClipboard::getDataInFormat(), QClipboardWatcher::getDataInFormat(), Maemo::GConfItemFast::getEntries(), getFcPattern(), QGtkStylePrivate::getFilesystemIcon(), getFullPath(), QFileSystemEngine::getLinkTarget(), getNetWmState(), QWaylandReadbackEglContext::getProcAddress(), QWaylandReadbackGlxContext::getProcAddress(), QGLXContext::getProcAddress(), QWaylandXCompositeGLXContext::getProcAddress(), QGLContext::getProcAddress(), QFontEngineMac::getSfntTable(), QFontEngine::getSfntTable(), QNetworkSessionPrivateImpl::getStatistics(), getWinLocaleName(), QXcbNativeInterface::graphicsDeviceForWidget(), QHttpNetworkReplyPrivate::gunzipBodyPartially(), QXlibKeyboard::handleKeyEvent(), QXlibClipboard::handleSelectionRequest(), QBenchmarkValgrindUtils::haveValgrind(), QRingBuffer< T >::indexOf(), QSqlDatabasePrivate::init(), QSslSocketBackendPrivate::initSslContext(), QTextLine::layout_helper(), QUnixSocketServer::listen(), QAxServerBase::Load(), QLibraryPrivate::load_sys(), loadFc(), loadRaw(), loadWin(), QFontDatabase::loadXlfd(), macQueryInternal(), macValue(), QXlibMime::mimeConvertToFormat(), QXlibMime::mimeDataForAtom(), QX11Data::motifdndObtainData(), QTest::mouseEvent(), QNativeSocketEnginePrivate::nativeBind(), normalizeTypeInternal(), QIBaseDriver::open(), QODBCDriver::open(), QWSSoundServerPrivate::openFile(), operator+=(), operator<<(), QUuid::operator<<(), QUuid::operator>>(), operator>>(), QBitArray::operator^=(), QBitArray::operator|=(), QBitArray::operator~(), QPdf::patternForBrush(), QSslSocketPrivate::peek(), QRingBuffer< T >::peek(), QDirectFBWindowSurface::permanentState(), QWSLocalMemSurface::permanentState(), QWSSharedMemSurface::permanentState(), QWSOnScreenSurface::permanentState(), QWSYellowSurface::permanentState(), QODBCDriver::primaryIndex(), QTest::printBenchmarkResult(), QDeclarativeBindingCompiler::program(), q_fromPercentEncoding(), q_toPercentEncoding(), qax_noSuchFunction(), qax_readClassInfo(), QBitArray::QBitArray(), QSslCertificatePrivate::QByteArray_from_X509(), qbytearray_insert(), qCompress(), qCreatev2Hash(), qErrnoWarning(), QTest::qExec(), qExtractServerTime(), qFillBufferWithString(), qGetInterfaceType(), qgl_use_font(), QGLXContext::QGLXContext(), QLayout::QLayout(), qMakeOCINumber(), QTest::qPrintDataTags(), qstring_to_xtp(), qStringFromUcs2Le(), qt_create_commandline(), qt_error_string(), qt_fillFontDef(), qt_getLprPrinters(), qt_inflateGZipDataFrom(), qt_parseEtcLpPrinters(), qt_parsePrintersConf(), qt_parseSpoolInterface(), qt_read_xpm_image_or_array(), qt_x11_apply_settings_in_all_apps(), QFtpDTP::read(), QIODevice::read(), QByteDataBuffer::read(), QRingBuffer< T >::read(), read_xpm_body(), QIODevice::readAll(), QHttp::readAll(), QHttpNetworkReplyPrivate::readBodyFast(), QWinSettingsPrivate::readKey(), QIODevice::readLine(), QNetworkAccessFileBackend::readMoreFromFile(), QOCICols::readPiecewise(), QNonContiguousByteDeviceIoDeviceImpl::readPointer(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QODBCDriver::record(), QResource::registerResource(), QWinSettingsPrivate::remove(), removeDotsFromPath(), QCoreApplicationPrivate::removePostedEvent(), QInternalMimeData::renderDataHelper(), replace(), QMYSQLResult::reset(), QBitArray::resize(), QMainWindowLayoutState::restoreState(), QCryptographicHash::result(), QInternalMimeData::retrieveData(), rightJustified(), QKqueueFileSystemWatcherEngine::run(), QWindowsPipeWriter::run(), QDomDocumentPrivate::saveDocument(), QZipReaderPrivate::scanFiles(), QTcpServerConnection::send(), QmlOstPlugin::send(), QWaylandSelection::send(), send_selection(), QWSSoundServerClient::sendClientMessage(), QWSServerPrivate::sendQCopEvent(), QXlibClipboard::sendSelection(), QWinSettingsPrivate::set(), QDeclarativeParser::Object::setBindingBit(), QAxBase::setControl(), setData(), QXmlSimpleReader::setFeature(), QWidget::setLayout(), QWSQCopSendCommand::setMessage(), QBBClipboard::setMimeData(), setNum(), setRawData(), QWSIMResponseCommand::setResult(), sm_setProperty(), QSmSocketReceiver::socketActivated(), QFtpDTP::socketReadyRead(), standardLibraryErrorString(), QProcessPrivate::startDetached(), QXmlStreamReaderPrivate::startDocument(), QRawFont::supportedWritingSystems(), QODBCDriver::tables(), toBase64(), QUuid::toByteArray(), toHex(), toLatin1_helper(), toLower(), QSslKey::toPem(), toPercentEncoding(), QMetaObjectBuilder::toRelocatableData(), QUuid::toRfc4122(), toSQLTCHAR(), toUpper(), QXlibKeyboard::translateKeySym(), QXcbKeyboard::translateKeySym(), translateKeySym(), QNetworkDiskCachePrivate::uniqueFileName(), VARIANTToQVariant(), WinMain(), QRfbRawEncoder::write(), QRfbHextileEncoder< SRC >::write(), write_xbm_image(), QIBaseResultPrivate::writeArray(), QIBaseResultPrivate::writeBlob(), QPdfEnginePrivate::writeCompressed(), QPAGenerator::writeGMap(), QPFGenerator::writeGMap(), QClipboardINCRTransaction::x11Event(), QX11Data::xdndHandleSelectionRequest(), QX11Data::xdndMimeConvertToFormat(), QX11Data::xdndMimeDataForAtom(), xdndObtainData(), and QWinSettingsPrivate::~QWinSettingsPrivate().

430 { detach(); return d->data; }
Data * d
Definition: qbytearray.h:386
void detach()
Definition: qbytearray.h:435

◆ data() [2/2]

const char * QByteArray::data ( ) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 431 of file qbytearray.h.

432 { return d->data; }
Data * d
Definition: qbytearray.h:386

◆ data_ptr()

DataPtr & QByteArray::data_ptr ( )
inline
Warning
This function is not part of the public interface.

Definition at line 397 of file qbytearray.h.

Referenced by QBitArray::data_ptr().

397 { return d; }
Data * d
Definition: qbytearray.h:386

◆ detach()

void QByteArray::detach ( )
inline
Warning
This function is not part of the public interface.

Definition at line 435 of file qbytearray.h.

Referenced by begin(), data(), QBitArray::detach(), end(), getData(), nulTerminated(), QByteRef::operator=(), remove(), replace(), and QMacPasteboard::retrieveData().

436 { if (d->ref != 1 || d->data != d->array) realloc(d->size); }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)

◆ end() [1/2]

QByteArray::iterator QByteArray::end ( )
inline
Warning
This function is not part of the public interface.

Definition at line 499 of file qbytearray.h.

Referenced by QConcatenable< QByteArray >::appendTo(), lastIndexOfHelper(), repeated(), split(), and trimmed().

500 { detach(); return d->data + d->size; }
Data * d
Definition: qbytearray.h:386
void detach()
Definition: qbytearray.h:435

◆ end() [2/2]

QByteArray::const_iterator QByteArray::end ( ) const
inline
Warning
This function is not part of the public interface.

Definition at line 501 of file qbytearray.h.

502 { return d->data + d->size; }
Data * d
Definition: qbytearray.h:386

◆ endsWith() [1/3]

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.nokia.com/index.html");
if (url.endsWith(".html"))
...
See also
startsWith(), right()

Definition at line 2735 of file qbytearray.cpp.

Referenced by QFileSystemEngine::absoluteName(), MetaObjectGenerator::addProperty(), QScript::callQtMethod(), QCacheItem::canCompress(), QDeclarativeCompiler::compileAlias(), QDeclarativeListModelParser::compileProperty(), QScriptEnginePrivate::convertToNativeQObject(), convertTypes(), QScriptEnginePrivate::convertValue(), QScriptEnginePrivate::create(), MetaObjectGenerator::createPrototype(), QDeclarativePropertyPrivate::findSignalByName(), QHttpNetworkReplyPrivate::getChunkSize(), QDeclarativeCompiler::indexOfSignal(), QAxServerBase::Invoke(), QAxEventSink::Invoke(), QScriptEnginePrivate::jscValueToVariant(), QDeclarativeObjectMethodScriptClass::matchScore(), QAxMetaObject::paramType(), paramType(), qDBusParametersForMethod(), qDecodeDataUrl(), qErrnoWarning(), QTest::qSignalDumperCallback(), QAxServerBase::qt_metacall(), queuedConnectionTypes(), QVariantToVARIANT(), QDeclarativeXMLHttpRequest::readEncoding(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), QMimeDataPrivate::retrieveTypedData(), QFtpDTP::socketReadyRead(), QProcessPrivate::startDetached(), QProcessPrivate::startProcess(), QUrlPrivate::toEncoded(), QNetworkCookie::toRawForm(), and QScript::variantFromValue().

2736 {
2737  if (d == ba.d || ba.d->size == 0)
2738  return true;
2739  if (d->size < ba.d->size)
2740  return false;
2741  return memcmp(d->data + d->size - ba.d->size, ba.d->data, ba.d->size) == 0;
2742 }
Data * d
Definition: qbytearray.h:386

◆ endsWith() [2/3]

bool QByteArray::endsWith ( char  ch) const

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2770 of file qbytearray.cpp.

2771 {
2772  if (d->size == 0)
2773  return false;
2774  return d->data[d->size - 1] == ch;
2775 }
Data * d
Definition: qbytearray.h:386

◆ endsWith() [3/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2752 of file qbytearray.cpp.

2753 {
2754  if (!str || !*str)
2755  return true;
2756  int len = qstrlen(str);
2757  if (d->size < len)
2758  return false;
2759  return qstrncmp(d->data + d->size - len, str, len) == 0;
2760 }
int qstrncmp(const char *str1, const char *str2, uint len)
Definition: qbytearray.h:101
Data * d
Definition: qbytearray.h:386
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ expand()

void QByteArray::expand ( int  i)
private

Definition at line 1587 of file qbytearray.cpp.

Referenced by QByteRef::operator=().

1588 {
1589  resize(qMax(i + 1, d->size));
1590 }
Data * d
Definition: qbytearray.h:386
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
void resize(int size)
Sets the size of the byte array to size bytes.

◆ fill()

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()

Definition at line 1556 of file qbytearray.cpp.

Referenced by dumpRecursive(), QByteArray(), QTest::qSignalDumperCallback(), QTest::qSignalDumperCallbackSlot(), and qStringFromUcs2Le().

1557 {
1558  resize(size < 0 ? d->size : size);
1559  if (d->size)
1560  memset(d->data, ch, d->size);
1561  return *this;
1562 }
Data * d
Definition: qbytearray.h:386
void resize(int size)
Sets the size of the byte array to size bytes.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ fromBase64()

QByteArray QByteArray::fromBase64 ( const QByteArray base64)
static

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 2045.

See also
toBase64()

Definition at line 4184 of file qbytearray.cpp.

Referenced by QDeclarativeEnginePrivate::atob(), QAuthenticatorPrivate::calculateResponse(), QSslCertificatePrivate::certificatesFromPem(), createImageNode(), QSslKeyPrivate::derFromPem(), and qDecodeDataUrl().

4185 {
4186  unsigned int buf = 0;
4187  int nbits = 0;
4188  QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
4189 
4190  int offset = 0;
4191  for (int i = 0; i < base64.size(); ++i) {
4192  int ch = base64.at(i);
4193  int d;
4194 
4195  if (ch >= 'A' && ch <= 'Z')
4196  d = ch - 'A';
4197  else if (ch >= 'a' && ch <= 'z')
4198  d = ch - 'a' + 26;
4199  else if (ch >= '0' && ch <= '9')
4200  d = ch - '0' + 52;
4201  else if (ch == '+')
4202  d = 62;
4203  else if (ch == '/')
4204  d = 63;
4205  else
4206  d = -1;
4207 
4208  if (d != -1) {
4209  buf = (buf << 6) | d;
4210  nbits += 6;
4211  if (nbits >= 8) {
4212  nbits -= 8;
4213  tmp[offset++] = buf >> nbits;
4214  buf &= (1 << nbits) - 1;
4215  }
4216  }
4217  }
4218 
4219  tmp.truncate(offset);
4220  return tmp;
4221 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
char at(int i) const
Returns the character at index position i in the byte array.
Definition: qbytearray.h:413

◆ fromHex()

QByteArray QByteArray::fromHex ( const QByteArray hexEncoded)
static

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()

Definition at line 4234 of file qbytearray.cpp.

4235 {
4236  QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
4237  uchar *result = (uchar *)res.data() + res.size();
4238 
4239  bool odd_digit = true;
4240  for (int i = hexEncoded.size() - 1; i >= 0; --i) {
4241  int ch = hexEncoded.at(i);
4242  int tmp;
4243  if (ch >= '0' && ch <= '9')
4244  tmp = ch - '0';
4245  else if (ch >= 'a' && ch <= 'f')
4246  tmp = ch - 'a' + 10;
4247  else if (ch >= 'A' && ch <= 'F')
4248  tmp = ch - 'A' + 10;
4249  else
4250  continue;
4251  if (odd_digit) {
4252  --result;
4253  *result = tmp;
4254  odd_digit = false;
4255  } else {
4256  *result |= tmp << 4;
4257  odd_digit = true;
4258  }
4259  }
4260 
4261  res.remove(0, result - (const uchar *)res.constData());
4262  return res;
4263 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
unsigned char uchar
Definition: qglobal.h:994
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
char at(int i) const
Returns the character at index position i in the byte array.
Definition: qbytearray.h:413

◆ fromPercentEncoding()

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

Returns a decoded copy of the URI/URL-style percent-encoded input.

Since
4.4

The percent parameter allows you to replace the '' character for another (for instance, '_' or '=').

For example:

text.data(); // returns "Qt is great!"
See also
toPercentEncoding(), QUrl::fromPercentEncoding()

Definition at line 4354 of file qbytearray.cpp.

Referenced by qDecodeDataUrl().

4355 {
4356  if (input.isNull())
4357  return QByteArray(); // preserve null
4358  if (input.isEmpty())
4359  return QByteArray(input.data(), 0);
4360 
4361  QByteArray tmp = input;
4362  q_fromPercentEncoding(&tmp, percent);
4363  return tmp;
4364 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
static void q_fromPercentEncoding(QByteArray *ba, char percent)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
bool isNull() const
Returns true if this byte array is null; otherwise returns false.
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ fromRawData()

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

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[] = {
0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
...
0x6d, 0x5b
};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
...
Warning
A byte array created with fromRawData() is not null-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(), constData()

Definition at line 4121 of file qbytearray.cpp.

Referenced by QUrl::allEncodedQueryItemValues(), QUrl::allQueryItemValues(), QTiffHandler::canRead(), QSslCertificatePrivate::certificatesFromPem(), count(), QUrl::encodedQueryItemValue(), QTextStreamPrivate::fillReadBuffer(), QRasterPixmapData::fromData(), QVGPixmapData::fromData(), QPixmapData::fromData(), QGLPixmapData::fromData(), QImage::fromData(), getData(), QUrl::hasEncodedQueryItem(), ICOReader::iconAt(), QTextList::itemText(), QSvgIOHandlerPrivate::load(), QSslCertificatePrivate::QByteArray_from_X509(), QNonContiguousByteDeviceBufferImpl::QNonContiguousByteDeviceBufferImpl(), qt_socks5_set_host_address_and_port(), qt_socks5_set_host_name_and_port(), QXIMInputContext::QXIMInputContext(), read_xbm_body(), QUrl::removeAllEncodedQueryItems(), QUrl::removeEncodedQueryItem(), replace(), QOstDevicePrivate::RunL(), QWSIMEvent::setData(), QWSIMInitEvent::setData(), QWSFontEvent::setData(), QWSIMResponseCommand::setData(), setRawData(), QBBButtonEventNotifier::updateButtonStates(), Maemo::IAPConfPrivate::valueToVariant(), and QSocks5SocketEngine::write().

4122 {
4123  Data *x = static_cast<Data *>(qMalloc(sizeof(Data)));
4124  Q_CHECK_PTR(x);
4125  if (data) {
4126  x->data = const_cast<char *>(data);
4127  } else {
4128  x->data = x->array;
4129  size = 0;
4130  }
4131  x->ref = 1;
4132  x->alloc = x->size = size;
4133  *x->array = '\0';
4134  return QByteArray(x, 0, 0);
4135 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ indexOf() [1/4]

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

Returns the index position of the first occurrence of the character ch in the byte array, searching forward from index position from.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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(), contains()

Definition at line 2461 of file qbytearray.cpp.

Referenced by addDefaultArguments(), QAxEventSink::addSignal(), QOpenGLPaintEngine::begin(), buildParameterNames(), QSslCertificatePrivate::certificatesFromPem(), QTextCodec::codecForHtml(), QDeclarativeCompiler::compileAlias(), contains(), QWindowsMimeHtml::convertFromMime(), QWindowsMimeHtml::convertToMime(), count(), QUrlPrivate::createErrorString(), QFileSystemEngine::currentPath(), QSslKeyPrivate::derFromPem(), QDeclarativeCompiler::evaluateEnum(), QGLTextureGlyphCache::fillTexture(), QDeclarativeImportsPrivate::find(), QDeclarativePropertyPrivate::findSignalByName(), findSlot(), fontFile(), for(), QNetworkHeadersPrivate::fromHttpDate(), QScript::functionConnect(), generateInterfaceXml(), QHttpNetworkReplyPrivate::getChunkSize(), indexOf(), init_plugins(), QAxServerBase::Invoke(), QAxServerBase::Load(), QHostInfo::localDomainName(), QTest::memberName(), QWindowsLocalCodec::mibEnum(), QJpUnicodeConv::newConverter(), QUrlPrivate::normalized(), QAudioInputPrivate::open(), QAudioOutputPrivate::open(), MetaObjectGenerator::paramList(), parseHttpOptionHeader(), QBBNavigatorEventNotifier::parsePPS(), QBBButtonEventNotifier::parsePPS(), QAxMetaObject::parsePrototype(), QHttpNetworkReplyPrivate::parseStatus(), QNetworkAccessHttpBackend::postRequest(), QDBusConnectionPrivate::prepareHook(), QApplicationPrivate::process_cmdline(), qDecodeDataUrl(), QMetaMethod_name(), qt_read_xpm_image_or_array(), QUrlPrivate::queryItem(), QXIMInputContext::QXIMInputContext(), read_xbm_body(), MetaObjectGenerator::readFuncsInfo(), QConfFileSettingsPrivate::readIniFile(), QDBusConnectionPrivate::relaySignal(), MetaObjectGenerator::replacePrototype(), MetaObjectGenerator::replaceType(), QUrlPrivate::setEncodedUrl(), setupDBusInterface(), setupLocaleMapper(), and split().

2462 {
2463  if (from < 0)
2464  from = qMax(from + d->size, 0);
2465  if (from < d->size) {
2466  const char *n = d->data + from - 1;
2467  const char *e = d->data + d->size;
2468  while (++n != e)
2469  if (*n == ch)
2470  return n - d->data;
2471  }
2472  return -1;
2473 }
Data * d
Definition: qbytearray.h:386
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ indexOf() [2/4]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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.

Definition at line 2430 of file qbytearray.cpp.

2431 {
2432  const int ol = qstrlen(c);
2433  if (ol == 1)
2434  return indexOf(*c, from);
2435 
2436  const int l = d->size;
2437  if (from > d->size || ol + from > l)
2438  return -1;
2439  if (ol == 0)
2440  return from;
2441 
2442  return qFindByteArray(d->data, d->size, from, c, ol);
2443 }
int qFindByteArray(const char *haystack0, int haystackLen, int from, const char *needle0, int needleLen)
unsigned char c[8]
Definition: qnumeric_p.h:62
Data * d
Definition: qbytearray.h:386
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...
uint qstrlen(const char *str)
Definition: qbytearray.h:79
QFactoryLoader * l

◆ indexOf() [3/4]

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(), count()

Definition at line 2388 of file qbytearray.cpp.

2389 {
2390  const int ol = ba.d->size;
2391  if (ol == 0)
2392  return from;
2393  if (ol == 1)
2394  return indexOf(*ba.d->data, from);
2395 
2396  const int l = d->size;
2397  if (from > d->size || ol + from > l)
2398  return -1;
2399 
2400  return qFindByteArray(d->data, d->size, from, ba.d->data, ol);
2401 }
int qFindByteArray(const char *haystack0, int haystackLen, int from, const char *needle0, int needleLen)
Data * d
Definition: qbytearray.h:386
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...
QFactoryLoader * l

◆ indexOf() [4/4]

int QByteArray::indexOf ( const QString str,
int  from = 0 
) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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.

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 1008 of file qstring.h.

1009 { return indexOf(s.toAscii(), from); }
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...

◆ insert() [1/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 1936 of file qbytearray.cpp.

Referenced by charString(), QCoreWlanEngine::connectToId(), QSettingsPrivate::iniEscapedString(), replace(), and write_pbm_image().

1937 {
1938  return qbytearray_insert(this, i, &ch, 1);
1939 }
static QByteArray & qbytearray_insert(QByteArray *ba, int pos, const char *arr, int len)
Inserts len bytes from the array arr at position pos and returns a reference the modified byte array...

◆ insert() [2/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 1901 of file qbytearray.cpp.

1902 {
1903  return qbytearray_insert(this, i, str, qstrlen(str));
1904 }
static QByteArray & qbytearray_insert(QByteArray *ba, int pos, const char *arr, int len)
Inserts len bytes from the array arr at position pos and returns a reference the modified byte array...
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ insert() [3/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Since
4.6

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

Definition at line 1920 of file qbytearray.cpp.

1921 {
1922  return qbytearray_insert(this, i, str, len);
1923 }
static QByteArray & qbytearray_insert(QByteArray *ba, int pos, const char *arr, int len)
Inserts len bytes from the array arr at position pos and returns a reference the modified byte array...

◆ insert() [4/5]

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(), remove()

Definition at line 1863 of file qbytearray.cpp.

1864 {
1865  QByteArray copy(ba);
1866  return qbytearray_insert(this, i, copy.d->data, copy.d->size);
1867 }
static QByteArray & qbytearray_insert(QByteArray *ba, int pos, const char *arr, int len)
Inserts len bytes from the array arr at position pos and returns a reference the modified byte array...
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135

◆ insert() [5/5]

QByteArray & QByteArray::insert ( int  i,
const QString str 
)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Inserts the string str at index position i in the byte array.

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

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 998 of file qstring.h.

999 { return insert(i, s.toAscii()); }
QByteArray & insert(int i, char c)
Inserts character ch at index position i in the byte array.

◆ isDetached()

bool QByteArray::isDetached ( ) const
inline
Warning
This function is not part of the public interface.

Definition at line 437 of file qbytearray.h.

Referenced by QBitArray::isDetached().

438 { return d->ref == 1; }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139

◆ isEmpty()

bool QByteArray::isEmpty ( ) const
inline

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()

Definition at line 421 of file qbytearray.h.

Referenced by _q_dupEnvironment(), QFileSystemEngine::absoluteName(), QFontDatabasePrivate::addAppFont(), QPdfEnginePrivate::addBrushPattern(), QIcdEngine::addConfiguration(), QUrl::addEncodedQueryItem(), QNetworkAccessCache::addEntry(), QWizardPrivate::addField(), MetaObjectGenerator::addProperty(), QUrl::addQueryItem(), QBasicUnixFontDatabase::addTTFile(), QFontDatabasePrivate::addTTFile(), QByteDataBuffer::append(), QDBusMarshaller::append(), QDBusMarshaller::appendCrossMarshalling(), QWaylandWindowManagerIntegration::authenticateWithToken(), QJSDebuggerAgent::backtrace(), QPatternist::Base64Binary::base64Decode(), QTest::benchmarkResult2String(), QDeclarativeCompiler::buildPropertyOnAssignment(), QNetworkAccessAuthenticationManager::cacheProxyCredentials(), QGraphicsAnchorLayoutPrivate::calculateGraphs(), QAuthenticatorPrivate::calculateResponse(), QScript::callQtMethod(), QTiffPlugin::capabilities(), QJpegPlugin::capabilities(), QICOPlugin::capabilities(), QTgaPlugin::capabilities(), QSvgPlugin::capabilities(), QMngPlugin::capabilities(), checkSymbolFont(), classIDL(), QWSServerPrivate::cleanupFonts(), cleanupFontsDir(), QTextCodec::codecForName(), QDataWidgetMapperPrivate::commit(), QDeclarativeListModelParser::compile(), QDeclarativeListModelParser::compileProperty(), QDeclarativeCompiler::compileTree(), QVNCScreen::connect(), QUnixSocket::connect(), QDeclarativeEnginePrivate::consoleLog(), QMetaType::construct(), convertFlags(), QWindowsMimeText::convertToMime(), QWindowsMimeURI::convertToMime(), QBuiltInMimes::convertToMime(), QLastResortMimes::convertToMime(), QScriptEnginePrivate::convertValue(), create_wm_client_leader(), createContext(), MetaObjectGenerator::createPrototype(), createReadHandlerHelper(), QDBusArgumentPrivate::createSignature(), data(), QSslKeyPrivate::decodePem(), QEgl::defaultConfig(), QMetaType::destroy(), QWidget::destroy(), QAuthenticatorPrivate::digestMd5Response(), QIcdEngine::doRequestUpdate(), QDeclarativeXMLHttpRequest::downloadProgress(), QPdfBaseEnginePrivate::drawTextItem(), QDeclarativeCompiler::dumpStats(), QPSPrintEnginePrivate::emitPages(), enableHarfBuzz(), QHttpNetworkConnectionChannel::ensureConnection(), QDeclarativeObjectMethodScriptClass::enumType(), envVarLocale(), QNetworkAccessAuthenticationManager::fetchCachedProxyCredentials(), QNetworkAccessHttpBackend::fetchCacheMetaData(), QHttpNetworkReplyPrivate::findChallenge(), QDeclarativeXMLHttpRequest::findTextCodec(), QDBusMetaObjectGenerator::findType(), QDeclarativeXMLHttpRequest::finished(), QRasterWindowSurface::flush(), fontFile(), QImageReader::format(), QPatternist::HexBinary::fromLexical(), QHostInfoAgent::fromName(), fromPercentEncoding(), QUuid::fromRfc4122(), QDeclarativeCompiler::genComponent(), generateInterfaceXml(), QDeclarativeCompiler::genObject(), QDeclarativeCompiler::genObjectBody(), QFreetypeFace::getFace(), QIcdEngine::getIcdInitialState(), getMacLocaleName(), getWinLocaleName(), MetaObjectGenerator::guessTypes(), QHttpNetworkRequestPrivate::header(), huntAndEmit(), if(), QTest::incidentType2String(), QScript::indexOfMetaEnum(), QSslCertificatePrivate::init(), QSslSocketBackendPrivate::initSslContext(), QAxServerBase::Invoke(), QAxEventSink::Invoke(), QDeclarativeCompiler::isAttachedPropertyName(), QBitArray::isEmpty(), QPacket::isEmpty(), QUrl::isEmpty(), QLibraryPrivate::isPlugin(), QMetaType::isRegistered(), QSignalSpy::isValid(), QUnixSocketMessage::isValid(), QDeclarativeKeysAttached::keyPressed(), QBBSystemLocaleData::languageLocale(), QCoreApplication::libraryPaths(), QUnixSocketServer::listen(), QSvgIOHandlerPrivate::load(), QAxServerBase::Load(), QSvgIconEnginePrivate::loadDataForModeAndState(), QNetworkAccessHttpBackend::loadFromCacheIfAllowed(), QFontEngine::loadKerningPairs(), loadSingleEngine(), QMenuBarPrivate::macCreateMenuBar(), macQueryInternal(), QDataWidgetMapper::mappedPropertyName(), QUrlPrivate::mergePaths(), QTest::messageType2String(), QDeclarativeParser::Object::metaObject(), MetaObjectGenerator::metaObject(), QXlibMime::mimeConvertToFormat(), QX11Data::motifdndObtainData(), QPpmHandler::name(), nextField(), QAxEventSink::OnChanged(), QAxEventSink::OnRequestEdit(), QIBaseDriver::open(), QWSPcMouseHandlerPrivate::openDevices(), operator!=(), operator==(), QBlittablePixmapData::paintEngine(), QUrlPrivate::parse(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), QFtpDTP::parseDir(), QHttpNetworkReplyPrivate::parseHeader(), parseHeaderName(), QDBusMetaObjectGenerator::parseMethods(), QAxMetaObject::parsePrototype(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QDBusMetaObjectGenerator::parseSignals(), QIODevicePrivate::peek(), QHttpNetworkConnectionChannel::pipelineFlush(), QDataWidgetMapperPrivate::populate(), QHttpNetworkConnectionPrivate::prepareRequest(), QByteDataBuffer::prepend(), QTest::printBenchmarkResult(), QFontEngineFT::properties(), QDeclarativeDomProperty::propertyNameParts(), q_fromPercentEncoding(), q_toPercentEncoding(), qax_readClassInfo(), qDBusReplyFill(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), QDeclarativeGridScaledImage::QDeclarativeGridScaledImage(), QDeclarativeImportDatabase::QDeclarativeImportDatabase(), qDecodeDataUrl(), qDetectCPUFeatures(), QEglFSScreen::QEglFSScreen(), qEncodeHmacMd5(), qstrcmp(), qt_adopted_thread_watcher_function(), qt_create_commandline(), qt_getLprPrinters(), qt_inflateGZipDataFrom(), qt_init(), qt_mac_can_clickThrough(), QAxServerBase::qt_metacall(), queryFont(), QAxBase::querySubObject(), QVariantToVARIANT(), QVideoFrame::QVideoFrame(), read_xpm_body(), read_xpm_string(), QDeclarativeXMLHttpRequest::readEncoding(), MetaObjectGenerator::readFuncsInfo(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), QBBSystemLocaleData::regionLocale(), registerFont(), registerInterface(), registerType(), QWizardPrivate::removeFieldAt(), QInternalMimeData::renderDataHelper(), QNetworkAccessHttpBackend::replyDownloadMetaData(), QBBNavigatorEventNotifier::replyPPS(), QDeclarativeXmlListModel::requestFinished(), QDeclarativeXMLHttpRequest::requestFromUrl(), QWizardField::resolve(), QUrl::resolved(), QDeclarativePropertyPrivate::restore(), QHeaderView::restoreState(), QMainWindow::restoreState(), QCryptographicHash::result(), QInternalMimeData::retrieveData(), QMacPasteboard::retrieveData(), QMimeDataPrivate::retrieveTypedData(), QWindowsPipeWriter::run(), QAxServerBase::Save(), QPacketProtocol::send(), QWaylandSelection::send(), send_selection(), QSslCertificate::serialNumber(), QNetworkHeadersPrivate::setCookedHeader(), QTimeLinePrivate::setCurrentTime(), QStyledItemDelegate::setEditorData(), QItemDelegate::setEditorData(), QBBClipboard::setMimeData(), QMacPasteboard::setMimeData(), QStyledItemDelegate::setModelData(), QItemDelegate::setModelData(), QNetworkHeadersPrivate::setRawHeader(), setupDBusInterface(), setupLocaleMapper(), QSmSocketReceiver::socketActivated(), QProcessPrivate::startDetached(), QUrl::swap(), QNetworkSessionPrivateImpl::syncStateWithInterface(), QDeclarativeCompiler::testQualifiedEnumAssignment(), QImage::text(), QUrlPrivate::toEncoded(), QTextHtmlExporter::toHtml(), QSslKey::toPem(), toPercentEncoding(), QNetworkCookie::toRawForm(), QFontSubset::toTruetype(), QFontSubset::toType1(), QXlibKeyboard::translateKeySym(), QXcbKeyboard::translateKeySym(), translateKeySym(), translateWSAError(), QMetaType::typeName(), QSystemLocaleData::updateLocale(), QPropertyAnimationPrivate::updateMetaProperty(), QHttpNetworkRequestPrivate::uri(), MetaObjectGenerator::usertypeToString(), QIntValidator::validate(), QUrlPrivate::validate(), QDoubleValidatorPrivate::validateWithLocale(), QMetaEnum::valueToKeys(), VARIANTToQVariant(), variantToString(), QSslCertificate::version(), QTextDocumentWriter::write(), QSvgIconEngine::write(), QX11Data::xdndMimeConvertToFormat(), QHttpThreadDelegate::~QHttpThreadDelegate(), and QPacketAutoSend::~QPacketAutoSend().

422 { return d->size == 0; }
Data * d
Definition: qbytearray.h:386

◆ isNull()

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()

Definition at line 3485 of file qbytearray.cpp.

Referenced by digestMd5ResponseHelper(), QUrlPrivate::ensureEncodedParts(), QUrlPrivate::fragmentImpl(), fromPercentEncoding(), fromPercentEncodingHelper(), fromPercentEncodingMutable(), get_device_info(), QBitArray::isNull(), QUrlPrivate::mergePaths(), QJpUnicodeConv::newConverter(), nextField(), operator<<(), QNetworkHeadersPrivate::parseAndSetHeader(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QGLWindowSurface::QGLWindowSurface(), qt_aqua_guess_size(), qt_init(), replace(), QUrl::resolved(), QUrl::setEncodedFragment(), QUrl::setEncodedQuery(), QNetworkHeadersPrivate::setRawHeaderInternal(), toPercentEncoding(), QDBusMetaType::typeToSignature(), and QXmlSerializer::write().

3485 { return d == &shared_null; }
Data * d
Definition: qbytearray.h:386
static Data shared_null
Definition: qbytearray.h:384

◆ isSharedWith()

bool QByteArray::isSharedWith ( const QByteArray other) const
inline
Warning
This function is not part of the public interface.

Definition at line 185 of file qbytearray.h.

185 { return d == other.d; }
Data * d
Definition: qbytearray.h:386

◆ lastIndexOf() [1/4]

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

Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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(), contains()

Definition at line 2589 of file qbytearray.cpp.

Referenced by addDefaultArguments(), QAxBase::asVariant(), cacheForNamespace(), QTextCodec::codecForHtml(), QDeclarativeObjectMethodScriptClass::enumType(), fontFile(), QUrl::fromPunycode(), QScript::indexOfMetaEnum(), lastIndexOf(), QUrlPrivate::mergePaths(), QMetaObject::newInstance(), QMetaObject::property(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), MetaObjectGenerator::readFuncsInfo(), QDeclarativeCompiler::rewriteBinding(), and VARIANTToQVariant().

2590 {
2591  if (from < 0)
2592  from += d->size;
2593  else if (from > d->size)
2594  from = d->size-1;
2595  if (from >= 0) {
2596  const char *b = d->data;
2597  const char *n = d->data + from + 1;
2598  while (n-- != b)
2599  if (*n == ch)
2600  return n - b;
2601  }
2602  return -1;
2603 }
Data * d
Definition: qbytearray.h:386

◆ lastIndexOf() [2/4]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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.

Definition at line 2563 of file qbytearray.cpp.

2564 {
2565  const int ol = qstrlen(str);
2566  if (ol == 1)
2567  return lastIndexOf(*str, from);
2568 
2569  return lastIndexOfHelper(d->data, d->size, str, ol, from);
2570 }
static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
Data * d
Definition: qbytearray.h:386
int lastIndexOf(char c, int from=-1) const
Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from.
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ lastIndexOf() [3/4]

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(), count()

Definition at line 2526 of file qbytearray.cpp.

2527 {
2528  const int ol = ba.d->size;
2529  if (ol == 1)
2530  return lastIndexOf(*ba.d->data, from);
2531 
2532  return lastIndexOfHelper(d->data, d->size, ba.d->data, ol, from);
2533 }
static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
Data * d
Definition: qbytearray.h:386
int lastIndexOf(char c, int from=-1) const
Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from.

◆ lastIndexOf() [4/4]

int QByteArray::lastIndexOf ( const QString str,
int  from = -1 
) const
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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.

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 1010 of file qstring.h.

1011 { return lastIndexOf(s.toAscii(), from); }
int lastIndexOf(char c, int from=-1) const
Returns the index position of the last occurrence of character ch in the byte array, searching backward from index position from.

◆ left()

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
right(), mid(), startsWith(), truncate()

Definition at line 2790 of file qbytearray.cpp.

Referenced by QZipWriterPrivate::addEntry(), QScript::callQtMethod(), QTextCodec::codecForHtml(), QDeclarativeCompiler::compileAlias(), convertTypes(), QScriptEnginePrivate::convertValue(), QDeclarativeObjectMethodScriptClass::enumType(), QDeclarativeCompiler::evaluateEnum(), QDeclarativeImportsPrivate::find(), QDeclarativePropertyPrivate::findSignalByName(), fontFile(), for(), QScript::functionConnect(), generateInterfaceXml(), QScript::indexOfMetaEnum(), QAxServerBase::Invoke(), QScriptEnginePrivate::jscValueToVariant(), QXIMInputContext::language(), leftJustified(), QAxServerBase::Load(), QTest::memberName(), QUrlPrivate::mergePaths(), QWindowsLocalCodec::mibEnum(), operator<<(), QBBNavigatorEventNotifier::parsePPS(), QNetworkAccessHttpBackend::postRequest(), QMetaObject::property(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), QHttpMultiPartPrivate::QHttpMultiPartPrivate(), QMetaMethod_name(), qt_init(), read_xpm_body(), rightJustified(), setupDBusInterface(), QScript::variantFromValue(), VARIANTToQVariant(), wrapDSC(), and write_pbm_image().

2791 {
2792  if (len >= d->size)
2793  return *this;
2794  if (len < 0)
2795  len = 0;
2796  return QByteArray(d->data, len);
2797 }
Data * d
Definition: qbytearray.h:386
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ leftJustified()

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()

Definition at line 3429 of file qbytearray.cpp.

Referenced by qEncodeHmacMd5(), and qFillBufferWithString().

3430 {
3431  QByteArray result;
3432  int len = d->size;
3433  int padlen = width - len;
3434  if (padlen > 0) {
3435  result.resize(len+padlen);
3436  if (len)
3437  memcpy(result.d->data, d->data, len);
3438  memset(result.d->data+len, fill, padlen);
3439  } else {
3440  if (truncate)
3441  result = left(width);
3442  else
3443  result = *this;
3444  }
3445  return result;
3446 }
void truncate(int pos)
Truncates the byte array at index position pos.
QByteArray & fill(char c, int size=-1)
Sets every byte in the byte array to character ch.
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray left(int len) const
Returns a byte array that contains the leftmost len bytes of this byte array.
void resize(int size)
Sets the size of the byte array to size bytes.

◆ length()

int QByteArray::length ( ) const
inline

Same as size().

Definition at line 356 of file qbytearray.h.

Referenced by _q_dupEnvironment(), QFileSystemEngine::absoluteName(), QAxClientSite::activateObject(), QPdfEnginePrivate::addBrushPattern(), QCryptographicHash::addData(), addDefaultArguments(), QZipWriterPrivate::addEntry(), QDBusMarshaller::append(), cacheForNamespace(), QTextCodec::canEncode(), QUrlPrivate::canonicalHost(), charString(), QPatternist::XsdTypeChecker::checkConstrainingFacetsBinary(), checkStaticArray(), QZipWriter::close(), QDeclarativeListModelParser::compileProperty(), QMetaObject::connectSlotsByName(), convertFlags(), QWindowsMimeHtml::convertFromMime(), QAbstractConcatenable::convertToAscii(), convertTypes(), MetaObjectGenerator::createPrototype(), QAuthenticatorPrivate::digestMd5Response(), QAxBase::dynamicCallHelper(), QPdfEnginePrivate::embedFont(), QDB2Result::exec(), QSymSQLResult::exec(), QODBCResult::exec(), QWSSoundServerPrivate::feedDevice(), QNetworkAccessHttpBackend::fetchCacheMetaData(), QDeclarativePropertyPrivate::findSignalByName(), findSlot(), fromPercentEncodingHelper(), fromPercentEncodingMutable(), QUuid::fromRfc4122(), QTextEncoder::fromUnicode(), getNetWmState(), QScript::QObjectDelegate::getOwnPropertyDescriptor(), QScript::QObjectDelegate::getOwnPropertySlot(), QWSPropertyManager::getProperty(), QFontEngineMac::getSfntTable(), QXmlStreamWriterPrivate::indent(), QDeclarativeCompiler::indexOfSignal(), QSettingsPrivate::iniEscapedKey(), QTestFileLogger::init(), QMetaMethod::invoke(), QAxServerBase::Invoke(), QDeclarativeCompiler::isSignalPropertyName(), QLibraryPrivate::load_sys(), MetaObjectGenerator::metaObject(), QJpUnicodeConv::newConverter(), QMetaObject::newInstance(), nextField(), nextNonWhitespace(), QUrlPrivate::normalized(), normalizeTypeInternal(), QIBaseDriver::open(), QTextStream::operator<<(), MetaObjectGenerator::paramList(), paramType(), parseDateString(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), parseHttpOptionHeader(), QDBusMetaObjectGenerator::parseMethods(), QAxMetaObject::parsePrototype(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QDBusMetaObjectGenerator::parseSignals(), QHttpNetworkReplyPrivate::parseStatus(), QPdf::patternForBrush(), QSslSocketPrivate::peek(), QApplicationPrivate::process_cmdline(), QCoreApplicationPrivate::processCommandLineArguments(), q_toPercentEncoding(), QByteArrayMatcher::QByteArrayMatcher(), qDBusParametersForMethod(), qEncodeHmacMd5(), qExtractSecurityPolicyFromString(), qFillBufferWithString(), qstrcmp(), qstring_to_xtp(), qStringFromUcs2Le(), qt_socks5_set_host_name_and_port(), QUuid::QUuid(), QVariantToVARIANT(), qvsnprintf(), QRingBuffer< T >::read(), read_xpm_body(), QHttpNetworkReplyPrivate::readHeader(), QConfFileSettingsPrivate::readIniFile(), QConfFileSettingsPrivate::readIniLine(), QHttpNetworkReplyPrivate::readStatus(), QMYSQLResult::reset(), runlengthEncode(), QZipReaderPrivate::scanFiles(), QTcpServerConnection::send(), QmlOstPlugin::send(), QWSSoundServerClient::sendClientMessage(), QWSServerPrivate::sendFontRemovedEvent(), QUrlPrivate::setEncodedUrl(), QWidgetPrivate::setWindowRole(), QXcbWindow::setWindowTitle(), QXlibWindow::setWindowTitle(), sm_setProperty(), QFontEngineXLFD::stringToCMap(), QString::toStdString(), QTest::toString(), QTextCodec::toUnicode(), QTextDecoder::toUnicode(), QMYSQLResult::virtual_hook(), wrapDSC(), QDBusMetaObjectGenerator::write(), write_pbm_image(), QPdfEnginePrivate::writeCompressed(), QPdfEnginePrivate::writeImage(), and QPdfEnginePrivate::~QPdfEnginePrivate().

356 { return d->size; }
Data * d
Definition: qbytearray.h:386

◆ mid()

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()

Definition at line 2835 of file qbytearray.cpp.

Referenced by addDefaultArguments(), RequestAnalyzer::analyze(), QAxBase::asVariant(), QAuthDevice::authorizeMessage(), QOpenGLPaintEngine::begin(), cacheForNamespace(), QTextCodec::codecForHtml(), QDeclarativeListModelParser::compileProperty(), QWindowsMimeHtml::convertToMime(), QScriptEnginePrivate::convertToNativeQObject(), QSslKeyPrivate::derFromPem(), QDeclarativeObjectMethodScriptClass::enumType(), QDeclarativeImportsPrivate::find(), QDeclarativePropertyPrivate::findSignalByName(), fontFile(), QHttpNetworkReplyPrivate::getChunkSize(), QScript::indexOfMetaEnum(), QDeclarativeCompiler::indexOfSignal(), QSettingsPrivate::iniUnescapedKey(), QAxServerBase::Invoke(), QTextList::itemText(), QHostInfo::localDomainName(), QJpUnicodeConv::newConverter(), nextField(), QAudioInputPrivate::open(), QAudioOutputPrivate::open(), MetaObjectGenerator::paramList(), parseDateString(), QHttpNetworkReplyPrivate::parseHeader(), QAuthenticatorPrivate::parseHttpResponse(), QBBNavigatorEventNotifier::parsePPS(), QBBButtonEventNotifier::parsePPS(), QAxMetaObject::parsePrototype(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QHttpNetworkReplyPrivate::parseStatus(), QNetworkAccessHttpBackend::postRequest(), QMetaObject::property(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), qDecodeDataUrl(), qNtlmDecodePhase2(), qt_init(), read_xpm_body(), QAuthDevice::readData(), QConfFileSettingsPrivate::readIniFile(), QAuthDevice::recvReadyRead(), QDeclarativeCompiler::rewriteBinding(), setupLocaleMapper(), split(), QSettingsPrivate::stringToVariant(), toType(), wrapDSC(), and QCoreApplicationData::~QCoreApplicationData().

2836 {
2837  if (d == &shared_null || d == &shared_empty || pos >= d->size)
2838  return QByteArray();
2839  if (len < 0)
2840  len = d->size - pos;
2841  if (pos < 0) {
2842  len += pos;
2843  pos = 0;
2844  }
2845  if (len + pos > d->size)
2846  len = d->size - pos;
2847  if (pos == 0 && len == d->size)
2848  return *this;
2849  return QByteArray(d->data + pos, len);
2850 }
Data * d
Definition: qbytearray.h:386
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ nulTerminated()

QByteArray QByteArray::nulTerminated ( ) const
private

Return a QByteArray that is sure to be NUL-terminated.

Warning
This function is not part of the public interface.

By default, all QByteArray have an extra NUL at the end, guaranteeing that assumption. However, if QByteArray::fromRawData is used, then the NUL is there only if the user put it there. We can't be sure.

Definition at line 1604 of file qbytearray.cpp.

Referenced by toDouble(), toLongLong(), toPercentEncoding(), and toULongLong().

1605 {
1606  // is this fromRawData?
1607  if (d->data == d->array)
1608  return *this; // no, then we're sure we're zero terminated
1609 
1610  QByteArray copy(*this);
1611  copy.detach();
1612  return copy;
1613 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135

◆ number() [1/5]

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

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(), toInt()

Definition at line 4004 of file qbytearray.cpp.

Referenced by QXmlTestLogger::addBenchmarkResult(), QTestLogger::addBenchmarkResult(), QDeclarativeCompiler::buildDynamicMeta(), classIDL(), QTextCodec::codecForMib(), convert(), QDeclarativeOpenMetaObjectType::createProperty(), QAuthenticatorPrivate::digestMd5Response(), QDeclarativeCompiledData::dump(), QDeclarativeCompiler::dumpStats(), QPSPrintEnginePrivate::flushPage(), QGLPixmapConvolutionFilter::generateConvolutionShader(), MetaObjectGenerator::guessTypes(), QHttpNetworkRequestPrivate::header(), QSettingsPrivate::iniEscapedString(), QFontDatabase::loadXlfd(), operator<<(), QNetworkAccessHttpBackend::postRequest(), QHttpNetworkConnectionPrivate::prepareRequest(), QFontEngine::properties(), prototype(), QAuthenticatorPrivate::QAuthenticatorPrivate(), qax_generateDocumentation(), qax_readClassInfo(), QHttpMultiPartPrivate::QHttpMultiPartPrivate(), QTest::qSignalDumperCallback(), QTest::qSignalDumperCallbackSlot(), QWSLock::QWSLock(), MetaObjectGenerator::readClassInfo(), MetaObjectGenerator::readEnumInfo(), MetaObjectGenerator::readEventInfo(), MetaObjectGenerator::readInterfaceInfo(), QBBSystemLocaleData::readPpsValue(), renameOverloads(), QSslCertificate::serialNumber(), QHttpNetworkHeaderPrivate::setContentLength(), QTimeLinePrivate::setCurrentTime(), QAxEventSink::signalHasReceivers(), QHttpSocketEngine::slotSocketConnected(), QTest::toString(), QFontSubset::toType1(), QFontSubset::type1AddedGlyphs(), QNetworkDiskCachePrivate::uniqueFileName(), QSslCertificate::version(), write_pbm_image(), and QWSLock::~QWSLock().

4005 {
4006  QByteArray s;
4007  s.setNum(n, base);
4008  return s;
4009 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ number() [2/5]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toUInt()

Definition at line 4016 of file qbytearray.cpp.

4017 {
4018  QByteArray s;
4019  s.setNum(n, base);
4020  return s;
4021 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ number() [3/5]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toLongLong()

Definition at line 4028 of file qbytearray.cpp.

4029 {
4030  QByteArray s;
4031  s.setNum(n, base);
4032  return s;
4033 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ number() [4/5]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toULongLong()

Definition at line 4040 of file qbytearray.cpp.

4041 {
4042  QByteArray s;
4043  s.setNum(n, base);
4044  return s;
4045 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ number() [5/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Format Meaning
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g use e or f format, whichever is the most concise
G use 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()

Definition at line 4079 of file qbytearray.cpp.

4080 {
4081  QByteArray s;
4082  s.setNum(n, f, prec);
4083  return s;
4084 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ operator const char *()

QByteArray::operator const char * ( ) const
inline

Definition at line 424 of file qbytearray.h.

425 { return d->data; }
Data * d
Definition: qbytearray.h:386

◆ operator QNoImplicitBoolCast()

QByteArray::operator QNoImplicitBoolCast ( ) const
private

◆ operator!=()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 983 of file qstring.h.

984 { return !qStringComparisonHelper(s, constData()); }
bool qStringComparisonHelper(const QString &s1, const char *s2)
Definition: qstring.h:916
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

◆ operator+=() [1/4]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 505 of file qbytearray.h.

506 { return append(c); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray & append(char c)
Appends the character ch to this byte array.

◆ operator+=() [2/4]

QByteArray & QByteArray::operator+= ( const char *  s)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str onto the end of this byte array and returns a reference to this byte array.

Definition at line 507 of file qbytearray.h.

508 { return append(s); }
QByteArray & append(char c)
Appends the character ch to this byte array.

◆ operator+=() [3/4]

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

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 this is an empty QByteArray, then this 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 this is not an empty QByteArray, 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(), prepend()

Definition at line 509 of file qbytearray.h.

510 { return append(a); }
QByteArray & append(char c)
Appends the character ch to this byte array.
long ASN1_INTEGER_get ASN1_INTEGER * a

◆ operator+=() [4/4]

QByteArray & QByteArray::operator+= ( const QString str)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the string str onto the end of this byte array and returns a reference to this byte array.

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

If the QString contains non-ASCII Unicode characters, using this operator can lead to loss of information. You can disable this operator by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 1006 of file qstring.h.

1007 { return operator+=(s.toAscii()); }
QByteArray & operator+=(char c)
Appends the character ch onto the end of this byte array and returns a reference to this byte array...
Definition: qbytearray.h:505

◆ operator<()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 985 of file qstring.h.

986 { return QString::fromAscii(constData(), size()) < s; }
static QString fromAscii(const char *, int size=-1)
Returns a QString initialized with the first size characters from the string str. ...
Definition: qstring.cpp:4276
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator<=()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 989 of file qstring.h.

990 { return QString::fromAscii(constData(), size()) <= s; }
static QString fromAscii(const char *, int size=-1)
Returns a QString initialized with the first size characters from the string str. ...
Definition: qstring.cpp:4276
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator=() [1/2]

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

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

Definition at line 935 of file qbytearray.cpp.

936 {
937  other.d->ref.ref();
938  if (!d->ref.deref())
939  qFree(d);
940  d = other.d;
941  return *this;
942 }
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139

◆ operator=() [2/2]

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

Assigns str to this byte array.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 954 of file qbytearray.cpp.

955 {
956  Data *x;
957  if (!str) {
958  x = &shared_null;
959  } else if (!*str) {
960  x = &shared_empty;
961  } else {
962  int len = qstrlen(str);
963  if (d->ref != 1 || len > d->alloc || (len < d->size && len < d->alloc >> 1))
964  realloc(len);
965  x = d;
966  memcpy(x->data, str, len + 1); // include null terminator
967  x->size = len;
968  }
969  x->ref.ref();
970  if (!d->ref.deref())
971  qFree(d);
972  d = x;
973  return *this;
974 }
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
uint qstrlen(const char *str)
Definition: qbytearray.h:79
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ operator==()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 981 of file qstring.h.

982 { return qStringComparisonHelper(s, constData()); }
bool qStringComparisonHelper(const QString &s1, const char *s2)
Definition: qstring.h:916
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

◆ operator>()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 987 of file qstring.h.

988 { return QString::fromAscii(constData(), size()) > s; }
static QString fromAscii(const char *, int size=-1)
Returns a QString initialized with the first size characters from the string str. ...
Definition: qstring.cpp:4276
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator>=()

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

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::toAscii().

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::fromAscii(), QString::fromLatin1(), QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

Definition at line 991 of file qstring.h.

992 { return QString::fromAscii(constData(), size()) >= s; }
static QString fromAscii(const char *, int size=-1)
Returns a QString initialized with the first size characters from the string str. ...
Definition: qstring.cpp:4276
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator[]() [1/4]

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

Same as at(i).

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 415 of file qbytearray.h.

Referenced by size().

416 { Q_ASSERT(uint(i) < uint(size())); return d->data[i]; }
Data * d
Definition: qbytearray.h:386
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int uint
Definition: qglobal.h:996
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator[]() [2/4]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 417 of file qbytearray.h.

418 { Q_ASSERT(i < uint(size())); return d->data[i]; }
Data * d
Definition: qbytearray.h:386
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
unsigned int uint
Definition: qglobal.h:996
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator[]() [3/4]

QByteRef QByteArray::operator[] ( int  i)
inline

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:

for (int i = 0; i < 10; ++i)
ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"

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.

See also
at()

Definition at line 489 of file qbytearray.h.

490 { Q_ASSERT(i >= 0); return QByteRef(*this, i); }
friend class QByteRef
Definition: qbytearray.h:392
#define Q_ASSERT(cond)
Definition: qglobal.h:1823

◆ operator[]() [4/4]

QByteRef QByteArray::operator[] ( uint  i)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 491 of file qbytearray.h.

492 { return QByteRef(*this, i); }
friend class QByteRef
Definition: qbytearray.h:392

◆ prepend() [1/4]

QByteArray & QByteArray::prepend ( char  ch)

Prepends the character ch to this byte array.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1694 of file qbytearray.cpp.

Referenced by QUrlPrivate::canonicalHost(), QCoreWlanEngine::connectToId(), QAuthenticatorPrivate::digestMd5Response(), QSettingsPrivate::iniEscapedKey(), normalizeTypeInternal(), prepend(), push_front(), qDecodeDataUrl(), qDetectCPUFeatures(), QXIMInputContext::QXIMInputContext(), QDeclarativeBindingCompilerPrivate::registerString(), QDBusAbstractAdaptor::setAutoRelaySignals(), and WinMain().

1695 {
1696  if (d->ref != 1 || d->size + 1 > d->alloc)
1697  realloc(qAllocMore(d->size + 1, sizeof(Data)));
1698  memmove(d->data+1, d->data, d->size);
1699  d->data[0] = ch;
1700  ++d->size;
1701  d->data[d->size] = '\0';
1702  return *this;
1703 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70

◆ prepend() [2/4]

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

Prepends the string str to this byte array.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 1657 of file qbytearray.cpp.

1658 {
1659  return prepend(str, qstrlen(str));
1660 }
QByteArray & prepend(char c)
Prepends the character ch to this byte array.
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ prepend() [3/4]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Since
4.6

Definition at line 1672 of file qbytearray.cpp.

1673 {
1674  if (str) {
1675  if (d->ref != 1 || d->size + len > d->alloc)
1676  realloc(qAllocMore(d->size + len, sizeof(Data)));
1677  memmove(d->data+len, d->data, d->size);
1678  memcpy(d->data, str, len);
1679  d->size += len;
1680  d->data[d->size] = '\0';
1681  }
1682  return *this;
1683 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70

◆ prepend() [4/4]

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 this is an empty QByteArray, then this 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 this is not an empty QByteArray, a deep copy of the data is performed, taking linear time.

See also
append(), insert()

Definition at line 1636 of file qbytearray.cpp.

1637 {
1638  if ((d == &shared_null || d == &shared_empty) && !IS_RAW_DATA(ba.d)) {
1639  *this = ba;
1640  } else if (ba.d != &shared_null) {
1641  QByteArray tmp = *this;
1642  *this = ba;
1643  append(tmp);
1644  }
1645  return *this;
1646 }
QByteArray & append(char c)
Appends the character ch to this byte array.
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define IS_RAW_DATA(d)
Definition: qbytearray.cpp:60
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ push_back() [1/3]

void QByteArray::push_back ( char  ch)
inline

Same as append(ch).

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 511 of file qbytearray.h.

512 { append(c); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray & append(char c)
Appends the character ch to this byte array.

◆ push_back() [2/3]

void QByteArray::push_back ( const char *  c)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Same as append(str).

Definition at line 513 of file qbytearray.h.

514 { append(c); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray & append(char c)
Appends the character ch to this byte array.

◆ push_back() [3/3]

void QByteArray::push_back ( const QByteArray other)
inline

This function is provided for STL compatibility.

It is equivalent to append(other).

Definition at line 515 of file qbytearray.h.

516 { append(a); }
QByteArray & append(char c)
Appends the character ch to this byte array.
long ASN1_INTEGER_get ASN1_INTEGER * a

◆ push_front() [1/3]

void QByteArray::push_front ( char  ch)
inline

Same as prepend(ch).

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 517 of file qbytearray.h.

518 { prepend(c); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray & prepend(char c)
Prepends the character ch to this byte array.

◆ push_front() [2/3]

void QByteArray::push_front ( const char *  c)
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Same as prepend(str).

Definition at line 519 of file qbytearray.h.

520 { prepend(c); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray & prepend(char c)
Prepends the character ch to this byte array.

◆ push_front() [3/3]

void QByteArray::push_front ( const QByteArray other)
inline

This function is provided for STL compatibility.

It is equivalent to prepend(other).

Definition at line 521 of file qbytearray.h.

522 { prepend(a); }
long ASN1_INTEGER_get ASN1_INTEGER * a
QByteArray & prepend(char c)
Prepends the character ch to this byte array.

◆ realloc()

void QByteArray::realloc ( int  alloc)
private

Definition at line 1564 of file qbytearray.cpp.

Referenced by append(), detach(), operator=(), prepend(), reserve(), and squeeze().

1565 {
1566  if (d->ref != 1 || d->data != d->array) {
1567  Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + alloc));
1568  Q_CHECK_PTR(x);
1569  x->size = qMin(alloc, d->size);
1570  ::memcpy(x->array, d->data, x->size);
1571  x->array[x->size] = '\0';
1572  x->ref = 1;
1573  x->alloc = alloc;
1574  x->data = x->array;
1575  if (!d->ref.deref())
1576  qFree(d);
1577  d = x;
1578  } else {
1579  Data *x = static_cast<Data *>(qRealloc(d, sizeof(Data) + alloc));
1580  Q_CHECK_PTR(x);
1581  x->alloc = alloc;
1582  x->data = x->array;
1583  d = x;
1584  }
1585 }
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
Q_CORE_EXPORT void * qRealloc(void *ptr, size_t size)
Definition: qmalloc.cpp:63
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853

◆ remove()

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(), replace()

Definition at line 1955 of file qbytearray.cpp.

Referenced by QFileSystemEngine::currentPath(), fromHex(), QFreetypeFace::getFace(), QHttpNetworkReplyPrivate::gunzipBodyPartially(), QX11Data::motifdndObtainData(), QMetaObject::newInstance(), normalizeTypeInternal(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), qDecodeDataUrl(), QFtpDTP::read(), read_xpm_string(), QStateMachinePrivate::registerSignalTransition(), QUrl::removeAllEncodedQueryItems(), QUrl::removeEncodedQueryItem(), and QWindowsPipeWriter::run().

1956 {
1957  if (len <= 0 || pos >= d->size || pos < 0)
1958  return *this;
1959  detach();
1960  if (pos + len >= d->size) {
1961  resize(pos);
1962  } else {
1963  memmove(d->data + pos, d->data + pos + len, d->size - pos - len);
1964  resize(d->size - len);
1965  }
1966  return *this;
1967 }
Data * d
Definition: qbytearray.h:386
void resize(int size)
Sets the size of the byte array to size bytes.
void detach()
Definition: qbytearray.h:435

◆ repeated()

QByteArray QByteArray::repeated ( int  times) const

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

Since
4.5

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

Example:

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

Definition at line 2337 of file qbytearray.cpp.

2338 {
2339  if (d->size == 0)
2340  return *this;
2341 
2342  if (times <= 1) {
2343  if (times == 1)
2344  return *this;
2345  return QByteArray();
2346  }
2347 
2348  const int resultSize = times * d->size;
2349 
2350  QByteArray result;
2351  result.reserve(resultSize);
2352  if (result.d->alloc != resultSize)
2353  return QByteArray(); // not enough memory
2354 
2355  memcpy(result.d->data, d->data, d->size);
2356 
2357  int sizeSoFar = d->size;
2358  char *end = result.d->data + sizeSoFar;
2359 
2360  const int halfResultSize = resultSize >> 1;
2361  while (sizeSoFar <= halfResultSize) {
2362  memcpy(end, result.d->data, sizeSoFar);
2363  end += sizeSoFar;
2364  sizeSoFar <<= 1;
2365  }
2366  memcpy(end, result.d->data, resultSize - sizeSoFar);
2367  result.d->data[resultSize] = '\0';
2368  result.d->size = resultSize;
2369  return result;
2370 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
void reserve(int size)
Attempts to allocate memory for at least size bytes.
Definition: qbytearray.h:449
iterator end()
Definition: qbytearray.h:499

◆ replace() [1/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces len bytes from index position pos with the zero terminated string after.

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

Definition at line 2002 of file qbytearray.cpp.

Referenced by addDefaultArguments(), QAxEventSink::addSignal(), QWindowsMimeHtml::convertToMime(), QFontEngine::convertToPostscriptFontFamilyName(), MetaObjectGenerator::guessTypes(), QLibraryPrivate::isPlugin(), MetaObjectGenerator::readFuncsInfo(), replace(), MetaObjectGenerator::replacePrototype(), MetaObjectGenerator::replaceType(), QUrlPrivate::setEncodedUrl(), QNetworkCookie::toRawForm(), and QFontSubset::toType1().

2003 {
2004  return replace(pos,len,after,qstrlen(after));
2005 }
uint qstrlen(const char *str)
Definition: qbytearray.h:79
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [2/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces len bytes from index position pos with alen bytes from the string after.

after is allowed to have '\0' characters.

Since
4.7

Definition at line 2016 of file qbytearray.cpp.

2017 {
2018  if (len == alen && (pos + len <= d->size)) {
2019  detach();
2020  memcpy(d->data + pos, after, len*sizeof(char));
2021  return *this;
2022  } else {
2023  remove(pos, len);
2024  return qbytearray_insert(this, pos, after, alen);
2025  }
2026 }
static QByteArray & qbytearray_insert(QByteArray *ba, int pos, const char *arr, int len)
Inserts len bytes from the array arr at position pos and returns a reference the modified byte array...
Data * d
Definition: qbytearray.h:386
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
void detach()
Definition: qbytearray.h:435

◆ replace() [3/14]

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(), remove()

Definition at line 1979 of file qbytearray.cpp.

1980 {
1981  if (len == after.d->size && (pos + len <= d->size)) {
1982  detach();
1983  memmove(d->data + pos, after.d->data, len*sizeof(char));
1984  return *this;
1985  } else {
1986  QByteArray copy(after);
1987  // ### optimize me
1988  remove(pos, len);
1989  return insert(pos, copy);
1990  }
1991 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
void detach()
Definition: qbytearray.h:435
QByteArray & insert(int i, char c)
Inserts character ch at index position i in the byte array.

◆ replace() [4/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the character before with the string after.

Definition at line 577 of file qbytearray.h.

578 { return replace(&before, 1, c, qstrlen(c)); }
unsigned char c[8]
Definition: qnumeric_p.h:62
uint qstrlen(const char *str)
Definition: qbytearray.h:79
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [5/14]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2247 of file qbytearray.cpp.

2248 {
2249  char b[2] = { before, '\0' };
2250  QByteArray cb = fromRawData(b, 1);
2251  return replace(cb, after);
2252 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static QByteArray fromRawData(const char *, int size)
Constructs a QByteArray that uses the first size bytes of the data array.
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [6/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the string after.

Definition at line 581 of file qbytearray.h.

582 { return replace(before, qstrlen(before), after, qstrlen(after)); }
uint qstrlen(const char *str)
Definition: qbytearray.h:79
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [7/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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 zero-terminated.

Definition at line 2082 of file qbytearray.cpp.

2083 {
2084  if (isNull() || (before == after && bsize == asize))
2085  return *this;
2086 
2087  // protect against before or after being part of this
2088  const char *a = after;
2089  const char *b = before;
2090  if (after >= d->data && after < d->data + d->size) {
2091  char *copy = (char *)malloc(asize);
2092  Q_CHECK_PTR(copy);
2093  memcpy(copy, after, asize);
2094  a = copy;
2095  }
2096  if (before >= d->data && before < d->data + d->size) {
2097  char *copy = (char *)malloc(bsize);
2098  Q_CHECK_PTR(copy);
2099  memcpy(copy, before, bsize);
2100  b = copy;
2101  }
2102 
2103  QByteArrayMatcher matcher(before, bsize);
2104  int index = 0;
2105  int len = d->size;
2106  char *d = data();
2107 
2108  if (bsize == asize) {
2109  if (bsize) {
2110  while ((index = matcher.indexIn(*this, index)) != -1) {
2111  memcpy(d + index, after, asize);
2112  index += bsize;
2113  }
2114  }
2115  } else if (asize < bsize) {
2116  uint to = 0;
2117  uint movestart = 0;
2118  uint num = 0;
2119  while ((index = matcher.indexIn(*this, index)) != -1) {
2120  if (num) {
2121  int msize = index - movestart;
2122  if (msize > 0) {
2123  memmove(d + to, d + movestart, msize);
2124  to += msize;
2125  }
2126  } else {
2127  to = index;
2128  }
2129  if (asize) {
2130  memcpy(d + to, after, asize);
2131  to += asize;
2132  }
2133  index += bsize;
2134  movestart = index;
2135  num++;
2136  }
2137  if (num) {
2138  int msize = len - movestart;
2139  if (msize > 0)
2140  memmove(d + to, d + movestart, msize);
2141  resize(len - num*(bsize-asize));
2142  }
2143  } else {
2144  // the most complex case. We don't want to lose performance by doing repeated
2145  // copies and reallocs of the string.
2146  while (index != -1) {
2147  uint indices[4096];
2148  uint pos = 0;
2149  while(pos < 4095) {
2150  index = matcher.indexIn(*this, index);
2151  if (index == -1)
2152  break;
2153  indices[pos++] = index;
2154  index += bsize;
2155  // avoid infinite loop
2156  if (!bsize)
2157  index++;
2158  }
2159  if (!pos)
2160  break;
2161 
2162  // we have a table of replacement positions, use them for fast replacing
2163  int adjust = pos*(asize-bsize);
2164  // index has to be adjusted in case we get back into the loop above.
2165  if (index != -1)
2166  index += adjust;
2167  int newlen = len + adjust;
2168  int moveend = len;
2169  if (newlen > len) {
2170  resize(newlen);
2171  len = newlen;
2172  }
2173  d = this->d->data;
2174 
2175  while(pos) {
2176  pos--;
2177  int movestart = indices[pos] + bsize;
2178  int insertstart = indices[pos] + pos*(asize-bsize);
2179  int moveto = insertstart + asize;
2180  memmove(d + moveto, d + movestart, (moveend - movestart));
2181  if (asize)
2182  memcpy(d + insertstart, after, asize);
2183  moveend = movestart - bsize;
2184  }
2185  }
2186  }
2187 
2188  if (a != after)
2189  ::free((char *)a);
2190  if (b != before)
2191  ::free((char *)b);
2192 
2193 
2194  return *this;
2195 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386
long ASN1_INTEGER_get ASN1_INTEGER * a
unsigned int uint
Definition: qglobal.h:996
The QByteArrayMatcher class holds a sequence of bytes that can be quickly matched in a byte array...
bool isNull() const
Returns true if this byte array is null; otherwise returns false.
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
void resize(int size)
Sets the size of the byte array to size bytes.
quint16 index

◆ replace() [8/14]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Example:

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

Definition at line 2044 of file qbytearray.cpp.

2045 {
2046  if (isNull() || before.d == after.d)
2047  return *this;
2048 
2049  QByteArray aft = after;
2050  if (after.d == d)
2051  aft.detach();
2052 
2053  return replace(before.constData(), before.size(), aft.constData(), aft.size());
2054 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
bool isNull() const
Returns true if this byte array is null; otherwise returns false.
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...
void detach()
Definition: qbytearray.h:435

◆ replace() [9/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the byte array before with the string after.

Definition at line 579 of file qbytearray.h.

580 { return replace(before.constData(), before.size(), c, qstrlen(c)); }
unsigned char c[8]
Definition: qnumeric_p.h:62
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
uint qstrlen(const char *str)
Definition: qbytearray.h:79
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [10/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the byte array after.

Definition at line 2064 of file qbytearray.cpp.

2065 {
2066  QByteArray aft = after;
2067  if (after.d == d)
2068  aft.detach();
2069 
2070  return replace(c, qstrlen(c), aft.constData(), aft.size());
2071 }
unsigned char c[8]
Definition: qnumeric_p.h:62
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
uint qstrlen(const char *str)
Definition: qbytearray.h:79
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...
void detach()
Definition: qbytearray.h:435

◆ replace() [11/14]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2288 of file qbytearray.cpp.

2289 {
2290  if (d->size) {
2291  char *i = data();
2292  char *e = i + d->size;
2293  for (; i != e; ++i)
2294  if (*i == before)
2295  * i = after;
2296  }
2297  return *this;
2298 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386

◆ replace() [12/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the string after.

Definition at line 1002 of file qstring.h.

1003 { return replace(before.toAscii(), after); }
QByteArray toAscii() const Q_REQUIRED_RESULT
Returns an 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4014
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [13/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the character before with the string after.

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 1000 of file qstring.h.

1001 { return replace(c, after.toAscii()); }
unsigned char c[8]
Definition: qnumeric_p.h:62
QByteArray toAscii() const Q_REQUIRED_RESULT
Returns an 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4014
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ replace() [14/14]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Replaces every occurrence of the string before with the byte array after.

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

If the QString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toAscii() (or QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

Definition at line 1004 of file qstring.h.

1005 { return replace(before.toAscii(), after); }
QByteArray toAscii() const Q_REQUIRED_RESULT
Returns an 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4014
QByteArray & replace(int index, int len, const char *s)
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ reserve()

void QByteArray::reserve ( int  size)
inline

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(), capacity()

Definition at line 449 of file qbytearray.h.

Referenced by _q_dupEnvironment(), QOCIResultPrivate::bindValue(), QUrlPrivate::canonicalHost(), QObject::connect(), QObject::disconnect(), QHttpNetworkRequestPrivate::header(), QSettingsPrivate::iniEscapedKey(), QSettingsPrivate::iniEscapedString(), QMetaMethod::invoke(), MetaObjectGenerator::metaObject(), nextField(), QUrlPrivate::normalized(), QMetaObject::normalizedSignature(), normalizeTypeInternal(), QIBaseDriver::open(), operator+=(), operator<<(), parseHttpOptionHeader(), QSslSocketPrivate::peek(), QNetworkAccessManagerPrivate::prepareMultipart(), QHttpNetworkReplyPrivate::readHeader(), QNetworkAccessFileBackend::readMoreFromFile(), QHttpNetworkReplyPrivate::readStatus(), repeated(), QSocks5SocketEnginePrivate::sendRequestMethod(), QSslCertificate::serialNumber(), QDBusPendingCallPrivate::setMetaTypes(), QLocalePrivate::validateChars(), QDBusMetaObjectGenerator::write(), and QSocks5SocketEngine::writeDatagram().

450 { if (d->ref != 1 || asize > d->alloc) realloc(asize); }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
void realloc(int alloc)

◆ resize()

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(), truncate()

Definition at line 1508 of file qbytearray.cpp.

Referenced by QNetworkReplyImplPrivate::_q_copyReadyRead(), QHttpPrivate::_q_slotReadyRead(), QZipWriterPrivate::addEntry(), QPdfEnginePrivate::addImage(), QPdf::ascii85Encode(), QPatternist::Base64Binary::base64Decode(), bindFont(), QDeclarativeBindingCompilerPrivate::buildExceptionData(), buildReverseMap(), chop(), QXlibClipboard::clipboardReadIncrementalProperty(), QX11Data::clipboardReadIncrementalProperty(), QXlibClipboard::clipboardReadProperty(), QX11Data::clipboardReadProperty(), QDeclarativeListModelParser::compile(), compressHelper(), QCoreWlanEngine::connectToId(), convertFlags(), QWindowsMimeText::convertFromMime(), QFontJis0201Codec::convertFromUnicode(), QGb18030Codec::convertFromUnicode(), QBig5Codec::convertFromUnicode(), QUtf8::convertFromUnicode(), QUtf16::convertFromUnicode(), QIconvCodec::convertFromUnicode(), QBig5hkscsCodec::convertFromUnicode(), QGbkCodec::convertFromUnicode(), QFontJis0208Codec::convertFromUnicode(), QEucKrCodec::convertFromUnicode(), QEucJpCodec::convertFromUnicode(), QSjisCodec::convertFromUnicode(), QGb2312Codec::convertFromUnicode(), QTsciiCodec::convertFromUnicode(), QFontBig5Codec::convertFromUnicode(), QCP949Codec::convertFromUnicode(), QFontGb2312Codec::convertFromUnicode(), QFontBig5hkscsCodec::convertFromUnicode(), QFontKsc5601Codec::convertFromUnicode(), QFontGbkCodec::convertFromUnicode(), QFontGb18030_0Codec::convertFromUnicode(), QWindowsLocalCodec::convertFromUnicode(), QIconvCodec::convertToUnicode(), QDB2Result::exec(), QODBCResult::exec(), expand(), QIBaseResultPrivate::fetchArray(), QIBaseResultPrivate::fetchBlob(), QXmlInputSource::fetchData(), QZipReader::fileData(), fill(), QAudioOutputPrivate::freeBlocks(), QPatternist::HexBinary::fromLexical(), generateGlyphTables(), generateHead(), generateHhea(), generateMaxp(), generateName(), QXmlStreamReaderPrivate::getChar_helper(), getGlyphData(), QFontEngine::getSfntTable(), QXlibKeyboard::handleKeyEvent(), leftJustified(), QAxServerBase::Load(), nextField(), normalizeTypeInternal(), operator+=(), operator>>(), QPdf::patternForBrush(), QSslSocketPrivate::peek(), QRingBuffer< T >::peek(), QHttpPrivate::postMoreData(), QDeclarativeBindingCompiler::program(), q_toPercentEncoding(), QBitArray::QBitArray(), QSslCertificatePrivate::QByteArray_from_X509(), qbytearray_insert(), qCompress(), qErrnoWarning(), qExtractServerTime(), qGetBinaryData(), qMakeOraDate(), qt_create_commandline(), qt_getLprPrinters(), qt_inflateGZipDataFrom(), qt_parseSpoolInterface(), QVideoFrame::QVideoFrame(), QIODevice::read(), QByteDataBuffer::read(), QRingBuffer< T >::read(), QIODevice::readAll(), QHttp::readAll(), QHttpNetworkReplyPrivate::readBodyFast(), QIODevice::readLine(), QNetworkAccessFileBackend::readMoreFromFile(), QOCICols::readPiecewise(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), remove(), QInternalMimeData::renderDataHelper(), replace(), QBitArray::resize(), QMainWindowLayoutState::restoreState(), QCryptographicHash::result(), rightJustified(), QKqueueFileSystemWatcherEngine::run(), simplified(), QFtpDTP::socketReadyRead(), toLatin1_helper(), QMetaObjectBuilder::toRelocatableData(), QXlibKeyboard::translateKeySym(), QXcbKeyboard::translateKeySym(), translateKeySym(), truncate(), VARIANTToQVariant(), QRfbRawEncoder::write(), QRfbHextileEncoder< SRC >::write(), QIBaseResultPrivate::writeArray(), QPdfEnginePrivate::writeCompressed(), QPAGenerator::writeGMap(), QPFGenerator::writeGMap(), and QXIMInputContext::x11FilterEvent().

1509 {
1510  if (size <= 0) {
1511  Data *x = &shared_empty;
1512  x->ref.ref();
1513  if (!d->ref.deref())
1514  qFree(d);
1515  d = x;
1516  } else if (d == &shared_null) {
1517  //
1518  // Optimize the idiom:
1519  // QByteArray a;
1520  // a.resize(sz);
1521  // ...
1522  // which is used in place of the Qt 3 idiom:
1523  // QByteArray a(sz);
1524  //
1525  Data *x = static_cast<Data *>(qMalloc(sizeof(Data)+size));
1526  Q_CHECK_PTR(x);
1527  x->ref = 1;
1528  x->alloc = x->size = size;
1529  x->data = x->array;
1530  x->array[size] = '\0';
1531  (void) d->ref.deref(); // cannot be 0, x points to shared_null
1532  d = x;
1533  } else {
1534  if (d->ref != 1 || size > d->alloc || (size < d->size && size < d->alloc >> 1))
1535  realloc(qAllocMore(size, sizeof(Data)));
1536  if (d->alloc >= size) {
1537  d->size = size;
1538  if (d->data == d->array) {
1539  d->array[size] = '\0';
1540  }
1541  }
1542  }
1543 }
Data * d
Definition: qbytearray.h:386
Q_CORE_EXPORT void qFree(void *ptr)
Definition: qmalloc.cpp:58
QBasicAtomicInt ref
Definition: qbytearray.h:139
Q_CORE_EXPORT void * qMalloc(size_t size)
Definition: qmalloc.cpp:53
void realloc(int alloc)
int qAllocMore(int alloc, int extra)
Definition: qbytearray.cpp:70
#define Q_CHECK_PTR(p)
Definition: qglobal.h:1853
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
static Data shared_null
Definition: qbytearray.h:384
static Data shared_empty
Definition: qbytearray.h:385

◆ right()

QByteArray QByteArray::right ( int  len) const

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()

Definition at line 2812 of file qbytearray.cpp.

Referenced by clientChallenge(), QApplicationPrivate::process_cmdline(), and QCoreApplicationPrivate::processCommandLineArguments().

2813 {
2814  if (len >= d->size)
2815  return *this;
2816  if (len < 0)
2817  len = 0;
2818  return QByteArray(d->data + d->size - len, len);
2819 }
Data * d
Definition: qbytearray.h:386
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ rightJustified()

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()

Definition at line 3466 of file qbytearray.cpp.

Referenced by classIDL(), and QSslCertificate::serialNumber().

3467 {
3468  QByteArray result;
3469  int len = d->size;
3470  int padlen = width - len;
3471  if (padlen > 0) {
3472  result.resize(len+padlen);
3473  if (len)
3474  memcpy(result.d->data+padlen, data(), len);
3475  memset(result.d->data, fill, padlen);
3476  } else {
3477  if (truncate)
3478  result = left(width);
3479  else
3480  result = *this;
3481  }
3482  return result;
3483 }
void truncate(int pos)
Truncates the byte array at index position pos.
QByteArray & fill(char c, int size=-1)
Sets every byte in the byte array to character ch.
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray left(int len) const
Returns a byte array that contains the leftmost len bytes of this byte array.
void resize(int size)
Sets the size of the byte array to size bytes.

◆ setNum() [1/8]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toShort()

Definition at line 584 of file qbytearray.h.

Referenced by QPdfEnginePrivate::drawTextItem(), number(), and setNum().

585 { return setNum(qlonglong(n), base); }
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584
qint64 qlonglong
Definition: qglobal.h:951

◆ setNum() [2/8]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toUShort()

Definition at line 586 of file qbytearray.h.

587 { return setNum(qulonglong(n), base); }
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584
quint64 qulonglong
Definition: qglobal.h:952

◆ setNum() [3/8]

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

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.

Example:

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(), toInt()

Definition at line 588 of file qbytearray.h.

589 { return setNum(qlonglong(n), base); }
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584
qint64 qlonglong
Definition: qglobal.h:951

◆ setNum() [4/8]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toUInt()

Definition at line 590 of file qbytearray.h.

591 { return setNum(qulonglong(n), base); }
static const uint base
Definition: qurl.cpp:268
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584
quint64 qulonglong
Definition: qglobal.h:952

◆ setNum() [5/8]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toLongLong()

Definition at line 3880 of file qbytearray.cpp.

3881 {
3882 #if defined(QT_CHECK_RANGE)
3883  if (base < 2 || base > 36) {
3884  qWarning("QByteArray::setNum: Invalid base %d", base);
3885  base = 10;
3886  }
3887 #endif
3888  QLocale locale(QLocale::C);
3889  *this = locale.d()->longLongToString(n, -1, base).toLatin1();
3890  return *this;
3891 }
static const uint base
Definition: qurl.cpp:268
Q_CORE_EXPORT void qWarning(const char *,...)

◆ setNum() [6/8]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

See also
toULongLong()

Definition at line 3899 of file qbytearray.cpp.

3900 {
3901 #if defined(QT_CHECK_RANGE)
3902  if (base < 2 || base > 36) {
3903  qWarning("QByteArray::setNum: Invalid base %d", base);
3904  base = 10;
3905  }
3906 #endif
3907  QLocale locale(QLocale::C);
3908  *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3909  return *this;
3910 }
static const uint base
Definition: qurl.cpp:268
Q_CORE_EXPORT void qWarning(const char *,...)

◆ setNum() [7/8]

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

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.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Note
The format of the number is not localized; the default C locale is used irrespective of the user's locale.
See also
toFloat()

Definition at line 592 of file qbytearray.h.

593 { return setNum(double(n),f,prec); }
QByteArray & setNum(short, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qbytearray.h:584

◆ setNum() [8/8]

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

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.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

The format f can be any of the following:

Format Meaning
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g use e or f format, whichever is the most concise
G use 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()

Definition at line 3943 of file qbytearray.cpp.

3944 {
3946  uint flags = 0;
3947 
3948  if (qIsUpper(f))
3950  f = qToLower(f);
3951 
3952  switch (f) {
3953  case 'f':
3955  break;
3956  case 'e':
3958  break;
3959  case 'g':
3961  break;
3962  default:
3963 #if defined(QT_CHECK_RANGE)
3964  qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3965 #endif
3966  break;
3967  }
3968 
3969  QLocale locale(QLocale::C);
3970  *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3971  return *this;
3972 }
Q_CORE_EXPORT void qWarning(const char *,...)
unsigned int uint
Definition: qglobal.h:996
static bool qIsUpper(char c)
Definition: qbytearray.cpp:637
static char qToLower(char c)
Definition: qbytearray.cpp:642

◆ setRawData()

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

Resets the QByteArray to use the first size bytes of the data array.

Since
4.7

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 existings QByteArray objects to save memory re-allocations.

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

Definition at line 4154 of file qbytearray.cpp.

4155 {
4156  if (d->ref != 1 || d->alloc) {
4157  *this = fromRawData(data, size);
4158  } else {
4159  if (data) {
4160  d->data = const_cast<char *>(data);
4161  } else {
4162  d->data = d->array;
4163  size = 0;
4164  }
4165  d->alloc = d->size = size;
4166  *d->array = '\0';
4167  }
4168  return *this;
4169 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
static QByteArray fromRawData(const char *, int size)
Constructs a QByteArray that uses the first size bytes of the data array.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ simplified()

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. 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()

Definition at line 3348 of file qbytearray.cpp.

Referenced by read_xpm_body(), and wrapDSC().

3349 {
3350  if (d->size == 0)
3351  return *this;
3352  QByteArray result(d->size, Qt::Uninitialized);
3353  const char *from = d->data;
3354  const char *fromend = from + d->size;
3355  int outc=0;
3356  char *to = result.d->data;
3357  for (;;) {
3358  while (from!=fromend && isspace(uchar(*from)))
3359  from++;
3360  while (from!=fromend && !isspace(uchar(*from)))
3361  to[outc++] = *from++;
3362  if (from!=fromend)
3363  to[outc++] = ' ';
3364  else
3365  break;
3366  }
3367  if (outc > 0 && to[outc-1] == ' ')
3368  outc--;
3369  result.resize(outc);
3370  return result;
3371 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
unsigned char uchar
Definition: qglobal.h:994

◆ size()

int QByteArray::size ( ) const
inline

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(), resize()

Definition at line 402 of file qbytearray.h.

Referenced by QSocks5SocketEnginePrivate::_q_controlSocketReadNotification(), QHttpPrivate::_q_slotConnected(), QHttpPrivate::_q_slotReadyRead(), QFtpPrivate::_q_startNextCommand(), QSocks5SocketEnginePrivate::_q_udpSocketReadNotification(), QZipWriterPrivate::addEntry(), QBasicUnixFontDatabase::addTTFile(), QFontDatabasePrivate::addTTFile(), QByteDataBuffer::append(), QString::append(), QHttpNetworkReplyPrivate::appendCompressedReplyData(), QNetworkReplyImplPrivate::appendDownstreamData(), QConcatenable< QByteArray >::appendTo(), Maemo::appendVariantToDBusMessage(), QApplicationPrivate::applyX11SpecificCommandLineArguments(), QPdf::ascii85Encode(), at(), QAuthDevice::authorizeMessage(), QPatternist::Base64Binary::base64Decode(), QSocks5PasswordAuthenticator::beginAuthenticate(), bindFont(), QOCIResultPrivate::bindValue(), QDeclarativeCompiler::buildDynamicMeta(), QDeclarativeBindingCompilerPrivate::buildExceptionData(), buildParameterNames(), buildString(), QFtpDTP::bytesAvailable(), QHttpNetworkReplyPrivate::bytesAvailable(), QScript::callQtMethod(), QTextCodec::canEncode(), QSslCertificatePrivate::certificatesFromDer(), QSslCertificatePrivate::certificatesFromPem(), QPicturePrivate::checkFormat(), checksum(), childKeysOrGroups(), QRingBuffer< T >::chop(), clientChallenge(), QXlibClipboard::clipboardReadIncrementalProperty(), QX11Data::clipboardReadIncrementalProperty(), QXlibClipboard::clipboardReadProperty(), QX11Data::clipboardReadProperty(), QTextCodec::codecForUtfText(), QUnixSocket::connect(), convertFlags(), QWindowsMimeText::convertFromMime(), QMacPasteboardMimeHTMLText::convertFromMime(), QMacPasteboardMimeTiff::convertFromMime(), QWindowsMimeHtml::convertFromMime(), QSimpleTextCodec::convertFromUnicode(), QIconvCodec::convertFromUnicode(), QWindowsLocalCodec::convertFromUnicode(), QAbstractConcatenable::convertToAscii(), QMacPasteboardMimePlainText::convertToMime(), QMacPasteboardMimeUnicodeText::convertToMime(), QWindowsMimeText::convertToMime(), QMacPasteboardMimeTiff::convertToMime(), QScriptEnginePrivate::convertToNativeQObject(), QIconvCodec::convertToUnicode(), QScriptEnginePrivate::convertValue(), QBitArray::count(), create_wm_client_leader(), QSslKeyPrivate::decodePem(), QSslKeyPrivate::derFromPem(), QIcdEngine::doRequestUpdate(), QPainterPrivate::draw_helper(), QPSPrintEnginePrivate::drawImageHelper(), QPdfEnginePrivate::embedFont(), QClipboardWatcher::empty(), QDB2Result::exec(), QSQLiteResult::exec(), QODBCResult::exec(), QOCICols::execBatch(), QHttpNetworkConnectionChannel::expand(), QFontEngineMac::faceId(), QZipReader::fileData(), QBitArray::fill(), QFileSystemEngine::fillMetaData(), QTextStreamPrivate::flushWriteBuffer(), QXlibClipboardMime::formats_sys(), QDB2Driver::formatValue(), QSqlDriver::formatValue(), QTDSDriver::formatValue(), QMYSQLDriver::formatValue(), QODBCDriver::formatValue(), QRingBuffer< T >::free(), fromBase64(), QImage::fromData(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), fromHex(), QUrl::fromPunycode(), QXmlInputSource::fromRawData(), fromRawData(), generateGlyphTables(), QDeclarativeCompiler::genObject(), QXmlStreamReaderPrivate::getChar_helper(), QHttpNetworkReplyPrivate::getChunkSize(), QXlibClipboard::getDataInFormat(), QClipboardWatcher::getDataInFormat(), QFreetypeFace::getFace(), getFullPath(), QFontEngine::glyphCount(), QHttpNetworkReplyPrivate::gunzipBodyPartially(), QHttpNetworkReplyPrivate::gzipCheckHeader(), QXlibKeyboard::handleKeyEvent(), QXlibClipboard::handleSelectionRequest(), QNonContiguousByteDeviceThreadForwardImpl::haveDataSlot(), QHttpNetworkRequestPrivate::header(), ICOReader::iconAt(), QByteArrayMatcher::indexIn(), indexOf(), QRingBuffer< T >::indexOf(), QSettingsPrivate::iniEscapedString(), QTestLiteStaticInfoPrivate::initializeSupportedAtoms(), QDeclarativeJS::integerFromString(), QScript::integerFromString(), QScriptEnginePrivate::jscValueToVariant(), QUnixSocketServer::listen(), QSvgIOHandlerPrivate::load(), QAxScriptManager::load(), QAxServerBase::Load(), QPixmap::loadFromData(), QImage::loadFromData(), QFontEngine::loadKerningPairs(), macQueryInternal(), macValue(), matchLineFeed(), QXlibMime::mimeConvertToFormat(), QXlibMime::mimeDataForAtom(), QRingBuffer< T >::nextDataBlockSize(), normalizeTypeInternal(), QIBaseDriver::open(), operator+(), operator+=(), QString::operator+=(), QString::operator<(), operator<<(), operator<<(), QString::operator<=(), operator=(), QString::operator=(), operator==(), QString::operator>(), QString::operator>=(), operator[](), QBitArray::operator^=(), QBitArray::operator|=(), QBitArray::operator~(), QDeclarativeCompiledData::pack(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QBufferPrivate::peek(), QIODevicePrivate::peek(), QRingBuffer< T >::peek(), QSslKeyPrivate::pemFromDer(), QByteDataBuffer::prepend(), QString::prepend(), QDeclarativeBindingCompiler::program(), QMacPasteboard::promiseKeeper(), QFtp::put(), QTextStreamPrivate::putString(), QBitArray::QBitArray(), QByteArray(), QSslCertificatePrivate::QByteArray_from_X509(), qbytearray_insert(), QByteArrayMatcher::QByteArrayMatcher(), QClipboardINCRTransaction::QClipboardINCRTransaction(), qCompress(), qCreatev2Hash(), qEncodeHmacMd5(), qEncodeNtlmBuffer(), qEncodeNtlmv2Response(), QFontEngineQPF::QFontEngineQPF(), qGetBinaryData(), qHash(), qMetaTypeCustomType_unlocked(), qNtlmDecodePhase2(), qStreamNtlmBuffer(), qStringFromUcs2Le(), qt_create_commandline(), qt_error_string(), qt_fill_input_buffer(), qt_get_net_supported(), qt_get_net_virtual_roots(), qt_inflateGZipDataFrom(), qt_mac_execute_apple_script(), qt_parse_pattern(), qt_read_xpm_image_or_array(), qt_socks5_get_host_address_and_port(), qt_x11_apply_settings_in_all_apps(), queryFont(), QUrlPrivate::queryItem(), qUncompress(), QFtpDTP::read(), QByteDataBuffer::read(), QIODevice::read(), QRingBuffer< T >::read(), read_xpm_body(), read_xpm_string(), QFtpDTP::readAll(), QIODevice::readAll(), QAuthDevice::readData(), QSocks5SocketEngine::readDatagram(), QConfFileSettingsPrivate::readIniFile(), QWinSettingsPrivate::readKey(), QIODevice::readLine(), QOCICols::readPiecewise(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkReplyPrivate::readStatus(), QPacketProtocolPrivate::readyToRead(), QAuthDevice::recvReadyRead(), registerFont(), QPlatformFontDatabase::registerQPF2Font(), releaseFontData(), removeDotsFromPath(), replace(), QBBNavigatorEventNotifier::replyPPS(), QRingBuffer< T >::reserve(), QBitArray::resize(), resize(), resolveGdi32(), QWidget::restoreGeometry(), QMainWindowLayoutState::restoreState(), QInternalMimeData::retrieveData(), QKqueueFileSystemWatcherEngine::run(), QDeclarativeVME::run(), QWindowsPipeWriter::run(), runlengthEncode(), QAxServerBase::Save(), QPacketProtocol::send(), send_selection(), QWSServerPrivate::sendQCopEvent(), QXlibClipboard::sendSelection(), QWinSettingsPrivate::set(), set_text(), QDeclarativeParser::Object::setBindingBit(), setData(), QWSRegionCommand::setData(), QUrlPrivate::setEncodedUrl(), QWSFontCommand::setFontName(), QWSQCopSendCommand::setMessage(), QBBClipboard::setMimeData(), QByteArrayMatcher::setPattern(), QWSDirectPainterSurface::setPermanentState(), QWSDisplay::setProperty(), setRawData(), QProcess::setReadChannel(), QWSIMResponseCommand::setResult(), QBitArray::size(), QNonContiguousByteDeviceByteArrayImpl::size(), QConcatenable< QByteArray >::size(), QByteDataBuffer::sizeNextBlock(), QFtpDTP::socketReadyRead(), standardLibraryErrorString(), QFontEngineMac::stringToCMap(), QRawFont::supportedWritingSystems(), toBase64(), toInt(), QSslKey::toPem(), QXlibKeyboard::translateKeySym(), QXcbKeyboard::translateKeySym(), translateKeySym(), truncate(), QIntValidator::validate(), QScript::variantFromValue(), VARIANTToQVariant(), QSettingsPrivate::variantToString(), Maemo::IAPConfPrivate::variantToValue(), QMYSQLResult::virtual_hook(), QIODevice::write(), QPdfEnginePrivate::write(), QRfbRawEncoder::write(), QXmlStreamWriterPrivate::write(), QUnixSocketPrivate::writeActivated(), QIBaseResultPrivate::writeBlob(), QPAGenerator::writeBlock(), QPFGenerator::writeBlock(), QPdfEnginePrivate::writeCompressed(), QUdpSocket::writeDatagram(), QSocks5SocketEngine::writeDatagram(), QPAGenerator::writeGMap(), QPFGenerator::writeGMap(), QClipboardINCRTransaction::x11Event(), QX11Data::xdndHandleSelectionRequest(), QX11Data::xdndMimeConvertToFormat(), QX11Data::xdndMimeDataForAtom(), and xdndObtainData().

403 { return d->size; }
Data * d
Definition: qbytearray.h:386

◆ split()

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.

Definition at line 2307 of file qbytearray.cpp.

Referenced by QGLXContext::getProcAddress(), QEgl::hasExtension(), QAxServerBase::Invoke(), QXlibMime::mimeDataForAtom(), MetaObjectGenerator::paramList(), parseCookieHeader(), QNetworkCookie::parseCookies(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), QBBNavigatorEventNotifier::parsePPS(), QBBButtonEventNotifier::parsePPS(), QAxMetaObject::parsePrototype(), QDeclarativeDomProperty::propertyNameParts(), q_hasEglExtension(), QGLXContext::QGLXContext(), qt_init(), QXIMInputContext::QXIMInputContext(), read_xpm_body(), QMimeDataPrivate::retrieveTypedData(), WinMain(), and QX11Data::xdndMimeDataForAtom().

2308 {
2309  QList<QByteArray> list;
2310  int start = 0;
2311  int end;
2312  while ((end = indexOf(sep, start)) != -1) {
2313  list.append(mid(start, end - start));
2314  start = end + 1;
2315  }
2316  list.append(mid(start));
2317  return list;
2318 }
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
QByteArray mid(int index, int len=-1) const
Returns a byte array containing len bytes from this byte array, starting at position pos...
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...
iterator end()
Definition: qbytearray.h:499

◆ squeeze()

void QByteArray::squeeze ( )
inline

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(), capacity()

Definition at line 452 of file qbytearray.h.

453 { if (d->size < d->alloc) realloc(d->size); }
Data * d
Definition: qbytearray.h:386
void realloc(int alloc)

◆ startsWith() [1/3]

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.nokia.com/");
if (url.startsWith("ftp:"))
...
See also
endsWith(), left()

Definition at line 2684 of file qbytearray.cpp.

Referenced by QFileSystemEngine::absoluteName(), QCoreApplication::arguments(), QHttpNetworkReplyPrivate::authenticationMethod(), cacheForNamespace(), QCacheItem::canCompress(), QUrlPrivate::canonicalHost(), QSvgIOHandler::canRead(), QNetworkAccessHttpBackend::canResume(), QDeclarativeListModelParser::compileProperty(), QScriptEnginePrivate::convertToNativeQObject(), QHttpNetworkConnectionChannel::detectPipeliningSupport(), QHttpNetworkReplyPrivate::findChallenge(), findSlot(), QUrl::fromPunycode(), QRegExpEngine::getEscape(), QFreetypeFace::getFace(), QDeclarativeCompiler::isSignalPropertyName(), QXIMInputContext::language(), QSvgTinyDocument::load(), QHostInfo::localDomainName(), QX11Data::motifdndObtainData(), QUrlPrivate::normalized(), QAuthenticatorPrivate::parseHttpResponse(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QHttpNetworkReplyPrivate::parseStatus(), QCoreApplicationPrivate::processCommandLineArguments(), qax_noSuchFunction(), qDecodeDataUrl(), QHttpNetworkReplyPrivate::readStatus(), QStateMachinePrivate::registerSignalTransition(), QUrlPrivate::toEncoded(), QNetworkCookie::toRawForm(), QIntValidator::validate(), QDoubleValidatorPrivate::validateWithLocale(), and QCoreApplicationData::~QCoreApplicationData().

2685 {
2686  if (d == ba.d || ba.d->size == 0)
2687  return true;
2688  if (d->size < ba.d->size)
2689  return false;
2690  return memcmp(d->data, ba.d->data, ba.d->size) == 0;
2691 }
Data * d
Definition: qbytearray.h:386

◆ startsWith() [2/3]

bool QByteArray::startsWith ( char  ch) const

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2719 of file qbytearray.cpp.

2720 {
2721  if (d->size == 0)
2722  return false;
2723  return d->data[0] == ch;
2724 }
Data * d
Definition: qbytearray.h:386

◆ startsWith() [3/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 2701 of file qbytearray.cpp.

2702 {
2703  if (!str || !*str)
2704  return true;
2705  int len = qstrlen(str);
2706  if (d->size < len)
2707  return false;
2708  return qstrncmp(d->data, str, len) == 0;
2709 }
int qstrncmp(const char *str1, const char *str2, uint len)
Definition: qbytearray.h:101
Data * d
Definition: qbytearray.h:386
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ swap()

void QByteArray::swap ( QByteArray other)
inline

Swaps byte array other with this byte array.

Since
4.8

This operation is very fast and never fails.

Definition at line 164 of file qbytearray.h.

164 { qSwap(d, other.d); }
Data * d
Definition: qbytearray.h:386
void qSwap(T &value1, T &value2)
Definition: qglobal.h:2181

◆ toBase64()

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 2045.

See also
fromBase64()

Definition at line 3796 of file qbytearray.cpp.

Referenced by QDeclarativeEnginePrivate::btoa(), QAuthenticatorPrivate::calculateResponse(), QSvgPaintEngine::drawImage(), operator<<(), QSslKeyPrivate::pemFromDer(), QSslCertificatePrivate::QByteArray_from_X509(), QHttpMultiPartPrivate::QHttpMultiPartPrivate(), and QPatternist::Base64Binary::stringValue().

3797 {
3798  const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3799  "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3800  const char padchar = '=';
3801  int padlen = 0;
3802 
3803  QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3804 
3805  int i = 0;
3806  char *out = tmp.data();
3807  while (i < d->size) {
3808  int chunk = 0;
3809  chunk |= int(uchar(d->data[i++])) << 16;
3810  if (i == d->size) {
3811  padlen = 2;
3812  } else {
3813  chunk |= int(uchar(d->data[i++])) << 8;
3814  if (i == d->size) padlen = 1;
3815  else chunk |= int(uchar(d->data[i++]));
3816  }
3817 
3818  int j = (chunk & 0x00fc0000) >> 18;
3819  int k = (chunk & 0x0003f000) >> 12;
3820  int l = (chunk & 0x00000fc0) >> 6;
3821  int m = (chunk & 0x0000003f);
3822  *out++ = alphabet[j];
3823  *out++ = alphabet[k];
3824  if (padlen > 1) *out++ = padchar;
3825  else *out++ = alphabet[l];
3826  if (padlen > 0) *out++ = padchar;
3827  else *out++ = alphabet[m];
3828  }
3829 
3830  tmp.truncate(out - tmp.data());
3831  return tmp;
3832 }
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
unsigned char uchar
Definition: qglobal.h:994
QFactoryLoader * l
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ toDouble()

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

Returns the byte array converted to a double value.

Returns 0.0 if the conversion fails.

If ok is not 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

QByteArray string("1234.56");
double a = string.toDouble(); // a == 1234.56
Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3763 of file qbytearray.cpp.

Referenced by getXDefault(), and toFloat().

3764 {
3766 }
static double bytearrayToDouble(const char *num, bool *ok, bool *overflow=0)
Definition: qlocale.cpp:3134
QByteArray nulTerminated() const
Return a QByteArray that is sure to be NUL-terminated.
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

◆ toFloat()

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

Returns the byte array converted to a float value.

Returns 0.0 if the conversion fails.

If ok is not 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3782 of file qbytearray.cpp.

Referenced by QOpenGLPaintEngine::begin().

3783 {
3784  return float(toDouble(ok));
3785 }
double toDouble(bool *ok=0) const
Returns the byte array converted to a double value.

◆ toHex()

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()

Definition at line 4271 of file qbytearray.cpp.

Referenced by digestMd5ResponseHelper(), QDBusMetaObjectGenerator::findType(), QDeclarativeEnginePrivate::md5(), QAuthenticatorPrivate::QAuthenticatorPrivate(), qmlsqldatabase_open_sync(), and QSslSocketBackendPrivate::startHandshake().

4272 {
4274  char *hexData = hex.data();
4275  const uchar *data = (const uchar *)d->data;
4276  for (int i = 0; i < d->size; ++i) {
4277  int j = (data[i] >> 4) & 0xf;
4278  if (j <= 9)
4279  hexData[i*2] = (j + '0');
4280  else
4281  hexData[i*2] = (j + 'a' - 10);
4282  j = data[i] & 0xf;
4283  if (j <= 9)
4284  hexData[i*2+1] = (j + '0');
4285  else
4286  hexData[i*2+1] = (j + 'a' - 10);
4287  }
4288  return hex;
4289 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
Data * d
Definition: qbytearray.h:386
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
Q_CORE_EXPORT QTextStream & hex(QTextStream &s)
for(int ii=mo->methodOffset();ii< mo->methodCount();++ii)
unsigned char uchar
Definition: qglobal.h:994

◆ toInt()

int QByteArray::toInt ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set 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()

Definition at line 3576 of file qbytearray.cpp.

Referenced by QBBScreen::adjustOrientation(), buttonChange(), QVNCScreen::connect(), QWSDisplay::Data::connectToPipe(), QWindowsMimeHtml::convertToMime(), QWidget::create(), QEglFSScreen::createAndSetPlatformContext(), createContext(), QEgl::defaultConfig(), defaultDepth(), do_size_hints(), QGraphicsScenePrivate::draw(), QNetworkAccessHttpBackend::fetchCacheMetaData(), QWidgetBackingStore::flushPaint(), flushUpdate(), QFreetypeFace::getFace(), QBBNavigatorEventNotifier::handleMessage(), QSettingsPrivate::iniUnescapedKey(), QGtkStylePrivate::isKDE4Session(), QScreen::isWidgetPaintOnScreen(), layoutDebug(), QWidgetPrivate::moveRect(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QHttpNetworkReplyPrivate::parseStatus(), QDBusConnectionPrivate::QDBusConnectionPrivate(), QEglFSScreen::QEglFSScreen(), qt_flush(), qt_grab_cursor(), qt_graphicsLayoutDebug(), QVNCDirtyMap::QVNCDirtyMap(), QVNCScreenPrivate::QVNCScreenPrivate(), QRfbSingleColorHextile< SRC >::read(), read_int_env_var(), QWidgetPrivate::scroll_sys(), QWidgetPrivate::scrollRect(), QDirectFBPaintEnginePrivate::setCompositionMode(), QVNCDirtyMapOptimized< T >::setDirty(), QPainter::setRenderHint(), QWidgetPrivate::subtractOpaqueSiblings(), and QETWidget::translateConfigEvent().

3577 {
3578  qlonglong v = toLongLong(ok, base);
3579  if (v < INT_MIN || v > INT_MAX) {
3580  if (ok)
3581  *ok = false;
3582  v = 0;
3583  }
3584  return int(v);
3585 }
qlonglong toLongLong(bool *ok=0, int base=10) const
Returns the byte array converted to a {long long} using base base, which is 10 by default and must be...
static const uint base
Definition: qurl.cpp:268
qint64 qlonglong
Definition: qglobal.h:951
#define INT_MAX

◆ toLong()

long QByteArray::toLong ( bool *  ok = 0,
int  base = 10 
) const
Since
4.1

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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set 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.
See also
number()

Definition at line 3641 of file qbytearray.cpp.

Referenced by QHttpNetworkReplyPrivate::getChunkSize().

3642 {
3643  qlonglong v = toLongLong(ok, base);
3644  if (v < LONG_MIN || v > LONG_MAX) {
3645  if (ok)
3646  *ok = false;
3647  v = 0;
3648  }
3649  return long(v);
3650 }
qlonglong toLongLong(bool *ok=0, int base=10) const
Returns the byte array converted to a {long long} using base base, which is 10 by default and must be...
static const uint base
Definition: qurl.cpp:268
qint64 qlonglong
Definition: qglobal.h:951

◆ toLongLong()

qlonglong QByteArray::toLongLong ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3508 of file qbytearray.cpp.

Referenced by parseHeaderValue(), toInt(), toLong(), and toShort().

3509 {
3510 #if defined(QT_CHECK_RANGE)
3511  if (base != 0 && (base < 2 || base > 36)) {
3512  qWarning("QByteArray::toLongLong: Invalid base %d", base);
3513  base = 10;
3514  }
3515 #endif
3516 
3518 }
static qint64 bytearrayToLongLong(const char *num, int base, bool *ok, bool *overflow=0)
Definition: qlocale.cpp:3186
static const uint base
Definition: qurl.cpp:268
Q_CORE_EXPORT void qWarning(const char *,...)
QByteArray nulTerminated() const
Return a QByteArray that is sure to be NUL-terminated.
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

◆ toLower()

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 NOKIA");
// y == "qt by nokia"
See also
toUpper(), {8-bit Character Comparisons}

Definition at line 2861 of file qbytearray.cpp.

Referenced by QHttpNetworkReplyPrivate::authenticationMethod(), QUrlPrivate::canonicalHost(), QTextCodec::codecForHtml(), createReadHandlerHelper(), digestMd5ResponseHelper(), QNetworkAccessHttpBackend::fetchCacheMetaData(), QDeclarativeXMLHttpRequest::fillHeadersList(), QHttpNetworkReplyPrivate::findChallenge(), fontFile(), get_named_rgb(), if(), imageReadMimeFormats(), imageWriteMimeFormats(), QWaylandNativeInterface::nativeResourceForWidget(), QAuthenticatorPrivate::parseHttpResponse(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), qax_noSuchFunction(), qDecodeDataUrl(), qt_fillFontDef(), read_xpm_body(), QHttpNetworkReplyPrivate::readHeader(), QPpmHandler::setOption(), WinMain(), and QTextDocumentWriter::write().

2862 {
2863  QByteArray s(*this);
2864  register uchar *p = reinterpret_cast<uchar *>(s.data());
2865  if (p) {
2866  while (*p) {
2867  *p = QChar::toLower((ushort)*p);
2868  p++;
2869  }
2870  }
2871  return s;
2872 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
unsigned char uchar
Definition: qglobal.h:994
unsigned short ushort
Definition: qglobal.h:995
QChar toLower() const
Returns the lowercase equivalent if the character is uppercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1239

◆ toPercentEncoding()

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.

Since
4.4

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");
// prints "{a fi%73hy %73tring%3F}"

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

See also
fromPercentEncoding(), QUrl::toPercentEncoding()

Definition at line 4467 of file qbytearray.cpp.

4469 {
4470  if (isNull())
4471  return QByteArray(); // preserve null
4472  if (isEmpty())
4473  return QByteArray(data(), 0);
4474 
4475  QByteArray include2 = include;
4476  if (percent != '%') // the default
4477  if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4478  || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4479  || (percent >= 0x30 && percent <= 0x39) // DIGIT
4480  || percent == 0x2D // -
4481  || percent == 0x2E // .
4482  || percent == 0x5F // _
4483  || percent == 0x7E) // ~
4484  include2 += percent;
4485 
4486  QByteArray result = *this;
4487  q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4488 
4489  return result;
4490 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
bool isNull() const
Returns true if this byte array is null; otherwise returns false.
QByteArray nulTerminated() const
Return a QByteArray that is sure to be NUL-terminated.
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ toShort()

short QByteArray::toShort ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3704 of file qbytearray.cpp.

3705 {
3706  qlonglong v = toLongLong(ok, base);
3707  if (v < SHRT_MIN || v > SHRT_MAX) {
3708  if (ok)
3709  *ok = false;
3710  v = 0;
3711  }
3712  return short(v);
3713 }
qlonglong toLongLong(bool *ok=0, int base=10) const
Returns the byte array converted to a {long long} using base base, which is 10 by default and must be...
static const uint base
Definition: qurl.cpp:268
qint64 qlonglong
Definition: qglobal.h:951

◆ toUInt()

uint QByteArray::toUInt ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3607 of file qbytearray.cpp.

Referenced by qt_parse_pattern().

3608 {
3609  qulonglong v = toULongLong(ok, base);
3610  if (v > UINT_MAX) {
3611  if (ok)
3612  *ok = false;
3613  v = 0;
3614  }
3615  return uint(v);
3616 }
static const uint base
Definition: qurl.cpp:268
qulonglong toULongLong(bool *ok=0, int base=10) const
Returns the byte array converted to an {unsigned long long} using base base, which is 10 by default a...
unsigned int uint
Definition: qglobal.h:996
quint64 qulonglong
Definition: qglobal.h:952

◆ toULong()

ulong QByteArray::toULong ( bool *  ok = 0,
int  base = 10 
) const
Since
4.1

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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3673 of file qbytearray.cpp.

3674 {
3675  qulonglong v = toULongLong(ok, base);
3676  if (v > ULONG_MAX) {
3677  if (ok)
3678  *ok = false;
3679  v = 0;
3680  }
3681  return ulong(v);
3682 }
static const uint base
Definition: qurl.cpp:268
qulonglong toULongLong(bool *ok=0, int base=10) const
Returns the byte array converted to an {unsigned long long} using base base, which is 10 by default a...
unsigned long ulong
Definition: qglobal.h:997
quint64 qulonglong
Definition: qglobal.h:952

◆ toULongLong()

qulonglong QByteArray::toULongLong ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3541 of file qbytearray.cpp.

Referenced by QHttpNetworkHeaderPrivate::contentLength(), QNetworkAccessHttpBackend::postRequest(), toUInt(), toULong(), and toUShort().

3542 {
3543 #if defined(QT_CHECK_RANGE)
3544  if (base != 0 && (base < 2 || base > 36)) {
3545  qWarning("QByteArray::toULongLong: Invalid base %d", base);
3546  base = 10;
3547  }
3548 #endif
3549 
3551 }
static const uint base
Definition: qurl.cpp:268
Q_CORE_EXPORT void qWarning(const char *,...)
static quint64 bytearrayToUnsLongLong(const char *num, int base, bool *ok)
Definition: qlocale.cpp:3228
QByteArray nulTerminated() const
Return a QByteArray that is sure to be NUL-terminated.
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

◆ toUpper()

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 NOKIA");
// y == "QT BY NOKIA"
See also
toLower(), {8-bit Character Comparisons}

Definition at line 2884 of file qbytearray.cpp.

Referenced by QSslSocketBackendPrivate::startHandshake().

2885 {
2886  QByteArray s(*this);
2887  register uchar *p = reinterpret_cast<uchar *>(s.data());
2888  if (p) {
2889  while (*p) {
2890  *p = QChar::toUpper((ushort)*p);
2891  p++;
2892  }
2893  }
2894  return s;
2895 }
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
unsigned char uchar
Definition: qglobal.h:994
QChar toUpper() const
Returns the uppercase equivalent if the character is lowercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1287
unsigned short ushort
Definition: qglobal.h:995

◆ toUShort()

ushort QByteArray::toUShort ( bool *  ok = 0,
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 0: if a conversion error occurs, *{ok} is set to false; otherwise *{ok} is set to true.

Note
The conversion of the number is performed in the default C locale, irrespective of the user's locale.
See also
number()

Definition at line 3735 of file qbytearray.cpp.

3736 {
3737  qulonglong v = toULongLong(ok, base);
3738  if (v > USHRT_MAX) {
3739  if (ok)
3740  *ok = false;
3741  v = 0;
3742  }
3743  return ushort(v);
3744 }
static const uint base
Definition: qurl.cpp:268
qulonglong toULongLong(bool *ok=0, int base=10) const
Returns the byte array converted to an {unsigned long long} using base base, which is 10 by default a...
unsigned short ushort
Definition: qglobal.h:995
quint64 qulonglong
Definition: qglobal.h:952

◆ trimmed()

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. 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()

Definition at line 3388 of file qbytearray.cpp.

Referenced by QHttpNetworkReplyPrivate::authenticationMethod(), QHostInfo::localDomainName(), QJpUnicodeConv::newConverter(), nextField(), parseCookieHeader(), QHttpNetworkReplyPrivate::parseHeader(), parseHeaderValue(), QAuthenticatorPrivate::parseHttpResponse(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QDeclarativeGridScaledImage::QDeclarativeGridScaledImage(), qDecodeDataUrl(), read_xpm_body(), QConfFileSettingsPrivate::readIniFile(), QMimeDataPrivate::retrieveTypedData(), and QCoreApplicationData::~QCoreApplicationData().

3389 {
3390  if (d->size == 0)
3391  return *this;
3392  const char *s = d->data;
3393  if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3394  return *this;
3395  int start = 0;
3396  int end = d->size - 1;
3397  while (start<=end && isspace(uchar(s[start]))) // skip white space from start
3398  start++;
3399  if (start <= end) { // only white space
3400  while (end && isspace(uchar(s[end]))) // skip white space from end
3401  end--;
3402  }
3403  int l = end - start + 1;
3404  if (l <= 0) {
3405  shared_empty.ref.ref();
3406  return QByteArray(&shared_empty, 0, 0);
3407  }
3408  return QByteArray(s+start, l);
3409 }
Data * d
Definition: qbytearray.h:386
QBasicAtomicInt ref
Definition: qbytearray.h:139
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
unsigned char uchar
Definition: qglobal.h:994
QFactoryLoader * l
iterator end()
Definition: qbytearray.h:499
static Data shared_empty
Definition: qbytearray.h:385

◆ truncate()

void QByteArray::truncate ( int  pos)

Friends and Related Functions

◆ operator!=() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 533 of file qbytearray.h.

534 { return !(a1==a2); }

◆ operator!=() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 535 of file qbytearray.h.

536 { return a2 ? qstrcmp(a1,a2) != 0 : !a1.isEmpty(); }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ operator!=() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 537 of file qbytearray.h.

538 { return a1 ? qstrcmp(a1,a2) != 0 : !a2.isEmpty(); }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ operator+() [1/5]

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

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

See also
QByteArray::operator+=()

Definition at line 564 of file qbytearray.h.

565 { return QByteArray(a1) += a2; }
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ operator+() [2/5]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 566 of file qbytearray.h.

567 { return QByteArray(a1) += a2; }
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ operator+() [3/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 568 of file qbytearray.h.

569 { return QByteArray(a1) += a2; }
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ operator+() [4/5]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 570 of file qbytearray.h.

571 { return QByteArray(a1) += a2; }
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ operator+() [5/5]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 572 of file qbytearray.h.

573 { return QByteArray(&a1, 1) += a2; }
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400

◆ operator<() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 539 of file qbytearray.h.

Referenced by QElapsedTimer::operator!=().

540 { return qstrcmp(a1, a2) < 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator<() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 541 of file qbytearray.h.

542 { return qstrcmp(a1, a2) < 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator<() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 543 of file qbytearray.h.

544 { return qstrcmp(a1, a2) < 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator<<()

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

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

See also
{Serializing Qt Data Types}

Definition at line 2928 of file qbytearray.cpp.

Referenced by setNum().

2929 {
2930  if (ba.isNull() && out.version() >= 6) {
2931  out << (quint32)0xffffffff;
2932  return out;
2933  }
2934  return out.writeBytes(ba, ba.size());
2935 }
QDataStream & writeBytes(const char *, uint len)
Writes the length specifier len and the buffer s to the stream and returns a reference to the stream...
bool isNull() const
Returns true if this byte array is null; otherwise returns false.
int version() const
Returns the version number of the data serialization format.
Definition: qdatastream.h:212
unsigned int quint32
Definition: qglobal.h:938
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator<=() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 545 of file qbytearray.h.

546 { return qstrcmp(a1, a2) <= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator<=() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 547 of file qbytearray.h.

548 { return qstrcmp(a1, a2) <= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator<=() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 549 of file qbytearray.h.

550 { return qstrcmp(a1, a2) <= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator==() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 527 of file qbytearray.h.

528 { return (a1.size() == a2.size()) && (memcmp(a1.constData(), a2.constData(), a1.size())==0); }
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ operator==() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 529 of file qbytearray.h.

530 { return a2 ? qstrcmp(a1,a2) == 0 : a1.isEmpty(); }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ operator==() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 531 of file qbytearray.h.

532 { return a1 ? qstrcmp(a1,a2) == 0 : a2.isEmpty(); }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421

◆ operator>() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 551 of file qbytearray.h.

552 { return qstrcmp(a1, a2) > 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 553 of file qbytearray.h.

554 { return qstrcmp(a1, a2) > 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 555 of file qbytearray.h.

556 { return qstrcmp(a1, a2) > 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>=() [1/3]

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

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 557 of file qbytearray.h.

558 { return qstrcmp(a1, a2) >= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>=() [2/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 559 of file qbytearray.h.

560 { return qstrcmp(a1, a2) >= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>=() [3/3]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

Definition at line 561 of file qbytearray.h.

562 { return qstrcmp(a1, a2) >= 0; }
int qstrcmp(const char *str1, const char *str2)
A safe strcmp() function.
Definition: qbytearray.cpp:231

◆ operator>>()

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

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

See also
{Serializing Qt Data Types}

Definition at line 2948 of file qbytearray.cpp.

Referenced by setNum().

2949 {
2950  ba.clear();
2951  quint32 len;
2952  in >> len;
2953  if (len == 0xffffffff)
2954  return in;
2955 
2956  const quint32 Step = 1024 * 1024;
2957  quint32 allocated = 0;
2958 
2959  do {
2960  int blockSize = qMin(Step, len - allocated);
2961  ba.resize(allocated + blockSize);
2962  if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2963  ba.clear();
2965  return in;
2966  }
2967  allocated += blockSize;
2968  } while (allocated < len);
2969 
2970  return in;
2971 }
const int blockSize
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
void setStatus(Status status)
Sets the status of the data stream to the status given.
int readRawData(char *, int len)
Reads at most len bytes from the stream into s and returns the number of bytes read.
void resize(int size)
Sets the size of the byte array to size bytes.
unsigned int quint32
Definition: qglobal.h:938
void clear()
Clears the contents of the byte array and makes it empty.

◆ QByteRef

friend class QByteRef
friend

Definition at line 392 of file qbytearray.h.

Referenced by operator[]().

◆ qChecksum()

quint16 qChecksum ( const char *  data,
uint  len 
)
related

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

The checksum is independent of the byte order (endianness).

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

Definition at line 434 of file qbytearray.cpp.

Referenced by qstrncmp().

435 {
436  register quint16 crc = 0xffff;
437  uchar c;
438  const uchar *p = reinterpret_cast<const uchar *>(data);
439  while (len--) {
440  c = *p++;
441  crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
442  c >>= 4;
443  crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
444  }
445  return ~crc & 0xffff;
446 }
unsigned char c[8]
Definition: qnumeric_p.h:62
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
static const quint16 crc_tbl[16]
Definition: qbytearray.cpp:413
unsigned char uchar
Definition: qglobal.h:994
unsigned short quint16
Definition: qglobal.h:936

◆ qCompress() [1/2]

QByteArray qCompress ( const QByteArray data,
int  compressionLevel 
)
related

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()

Definition at line 604 of file qbytearray.h.

Referenced by qCompress(), and setNum().

605 { return qCompress(reinterpret_cast<const uchar *>(data.constData()), data.size(), compressionLevel); }
QByteArray qCompress(const QByteArray &data, int compressionLevel)
Compresses the data byte array and returns the compressed data in a new byte array.
Definition: qbytearray.h:604
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

◆ qCompress() [2/2]

QByteArray qCompress ( const uchar data,
int  nbytes,
int  compressionLevel 
)
related

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 483 of file qbytearray.cpp.

484 {
485  if (nbytes == 0) {
486  return QByteArray(4, '\0');
487  }
488  if (!data) {
489  qWarning("qCompress: Data is null");
490  return QByteArray();
491  }
492  if (compressionLevel < -1 || compressionLevel > 9)
493  compressionLevel = -1;
494 
495  ulong len = nbytes + nbytes / 100 + 13;
496  QByteArray bazip;
497  int res;
498  do {
499  bazip.resize(len + 4);
500  res = ::compress2((uchar*)bazip.data()+4, &len, (uchar*)data, nbytes, compressionLevel);
501 
502  switch (res) {
503  case Z_OK:
504  bazip.resize(len + 4);
505  bazip[0] = (nbytes & 0xff000000) >> 24;
506  bazip[1] = (nbytes & 0x00ff0000) >> 16;
507  bazip[2] = (nbytes & 0x0000ff00) >> 8;
508  bazip[3] = (nbytes & 0x000000ff);
509  break;
510  case Z_MEM_ERROR:
511  qWarning("qCompress: Z_MEM_ERROR: Not enough memory");
512  bazip.resize(0);
513  break;
514  case Z_BUF_ERROR:
515  len *= 2;
516  break;
517  }
518  } while (res == Z_BUF_ERROR);
519 
520  return bazip;
521 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
unsigned char uchar
Definition: qglobal.h:994
Q_CORE_EXPORT void qWarning(const char *,...)
unsigned long ulong
Definition: qglobal.h:997
void resize(int size)
Sets the size of the byte array to size bytes.

◆ qsnprintf()

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

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::sprintf() to format a string instead.
See also
qvsnprintf(), QString::sprintf()

Definition at line 128 of file qvsnprintf.cpp.

Referenced by fromPercentEncodingMutable(), qstrncmp(), qt_x_errhandler(), and write_xbm_image().

129 {
130  va_list ap;
131  va_start(ap, fmt);
132 
133  int ret = qvsnprintf(str, n, fmt, ap);
134  va_end(ap);
135 
136  return ret;
137 }
int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap)
A portable vsnprintf() function.
Definition: qvsnprintf.cpp:78

◆ qstrcmp()

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

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 0.

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

See also
qstrncmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}

Definition at line 231 of file qbytearray.cpp.

Referenced by convert(), operator!=(), operator<(), operator<=(), operator==(), operator>(), operator>=(), qstrcmp(), qstrnlen(), and QVariantToVARIANT().

232 {
233  return (str1 && str2) ? strcmp(str1, str2)
234  : (str1 ? 1 : (str2 ? -1 : 0));
235 }

◆ qstrcpy()

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

Copies all the characters up to and including the '\0' from src into dst and returns a pointer to dst.

If src is 0, it immediately returns 0.

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

See also
qstrncpy()

Definition at line 137 of file qbytearray.cpp.

Referenced by qstrdup(), qstrncmp(), and qstrnlen().

138 {
139  if (!src)
140  return 0;
141 #if defined(_MSC_VER) && _MSC_VER >= 1400
142  int len = qstrlen(src);
143  // This is actually not secure!!! It will be fixed
144  // properly in a later release!
145  if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
146  return dst;
147  return 0;
148 #else
149  return strcpy(dst, src);
150 #endif
151 }
uint qstrlen(const char *str)
Definition: qbytearray.h:79

◆ qstrdup()

char * qstrdup ( const char *  src)
related

Returns a duplicate string.

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

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

Definition at line 114 of file qbytearray.cpp.

115 {
116  if (!src)
117  return 0;
118  char *dst = new char[strlen(src) + 1];
119  return qstrcpy(dst, src);
120 }
char * qstrcpy(char *dst, const char *src)
Copies all the characters up to and including the &#39;\0&#39; from src into dst and returns a pointer to dst...
Definition: qbytearray.cpp:137

◆ qstricmp()

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

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 0.

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

See also
qstrcmp(), qstrncmp(), qstrnicmp(), {8-bit Character Comparisons}

Definition at line 279 of file qbytearray.cpp.

Referenced by classIDL(), nameMatch(), and qstrncmp().

280 {
281  register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
282  register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
283  int res;
284  uchar c;
285  if (!s1 || !s2)
286  return s1 ? 1 : (s2 ? -1 : 0);
287  for (; !(res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)); s1++, s2++)
288  if (!c) // strings are equal
289  break;
290  return res;
291 }
unsigned char c[8]
Definition: qnumeric_p.h:62
unsigned char uchar
Definition: qglobal.h:994
unsigned short ushort
Definition: qglobal.h:995
QChar toLower() const
Returns the lowercase equivalent if the character is uppercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1239

◆ QString

friend class QString
friend

Definition at line 393 of file qbytearray.h.

◆ qstrlen()

uint qstrlen ( const char *  str)
related

A safe strlen() function.

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

See also
qstrnlen()

Definition at line 79 of file qbytearray.h.

Referenced by append(), compare(), containsTLDEntry(), count(), endsWith(), indexOf(), insert(), lastIndexOf(), operator=(), prepend(), QByteArray(), qstrcpy(), qsvg_get_hex_rgb(), qt_get_hex_rgb(), removeGroupSeparators(), replace(), startsWith(), and write_xbm_image().

80 { return str ? uint(strlen(str)) : 0; }
unsigned int uint
Definition: qglobal.h:996

◆ qstrncmp()

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

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 0.

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

See also
qstrcmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}

Definition at line 101 of file qbytearray.h.

Referenced by endsWith(), read_dib_fileheader(), and startsWith().

102 {
103  return (str1 && str2) ? strncmp(str1, str2, len)
104  : (str1 ? 1 : (str2 ? -1 : 0));
105 }

◆ qstrncpy()

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

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 0, returns 0 immediately.

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

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()

Definition at line 175 of file qbytearray.cpp.

Referenced by qstrnlen().

176 {
177  if (!src || !dst)
178  return 0;
179 #if defined(_MSC_VER) && _MSC_VER >= 1400
180  strncpy_s(dst, len, src, len-1);
181 #else
182  strncpy(dst, src, len);
183 #endif
184  if (len > 0)
185  dst[len-1] = '\0';
186  return dst;
187 }

◆ qstrnicmp()

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

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 0.

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

See also
qstrcmp(), qstrncmp(), qstricmp(), {8-bit Character Comparisons}

Definition at line 316 of file qbytearray.cpp.

Referenced by qstrncmp().

317 {
318  register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
319  register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
320  int res;
321  uchar c;
322  if (!s1 || !s2)
323  return s1 ? 1 : (s2 ? -1 : 0);
324  for (; len--; s1++, s2++) {
325  if ((res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)))
326  return res;
327  if (!c) // strings are equal
328  break;
329  }
330  return 0;
331 }
unsigned char c[8]
Definition: qnumeric_p.h:62
unsigned char uchar
Definition: qglobal.h:994
unsigned short ushort
Definition: qglobal.h:995
QChar toLower() const
Returns the lowercase equivalent if the character is uppercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1239

◆ qstrnlen()

uint qstrnlen ( const char *  str,
uint  maxlen 
)
related
Since
4.2

A safe strnlen() function.

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

See also
qstrlen()

Definition at line 82 of file qbytearray.h.

83 {
84  uint length = 0;
85  if (str) {
86  while (length < maxlen && *str++)
87  length++;
88  }
89  return length;
90 }
unsigned int uint
Definition: qglobal.h:996
int length() const
Same as size().
Definition: qbytearray.h:356

◆ qUncompress [1/2]

QByteArray qUncompress ( const uchar data,
int  nbytes 
)
friend

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 562 of file qbytearray.cpp.

Referenced by qUncompress(), and setNum().

563 {
564  if (!data) {
565  qWarning("qUncompress: Data is null");
566  return QByteArray();
567  }
568  if (nbytes <= 4) {
569  if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
570  qWarning("qUncompress: Input data is corrupted");
571  return QByteArray();
572  }
573  ulong expectedSize = (data[0] << 24) | (data[1] << 16) |
574  (data[2] << 8) | (data[3] );
575  ulong len = qMax(expectedSize, 1ul);
577 
578  forever {
579  ulong alloc = len;
580  if (len >= ulong(1 << 31) - sizeof(QByteArray::Data)) {
581  //QByteArray does not support that huge size anyway.
582  qWarning("qUncompress: Input data is corrupted");
583  return QByteArray();
584  }
585  QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + alloc));
586  if (!p) {
587  // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
588  qWarning("qUncompress: could not allocate enough memory to uncompress data");
589  return QByteArray();
590  }
591  d.take(); // realloc was successful
592  d.reset(p);
593 
594  int res = ::uncompress((uchar*)d->array, &len,
595  (uchar*)data+4, nbytes-4);
596 
597  switch (res) {
598  case Z_OK:
599  if (len != alloc) {
600  if (len >= ulong(1 << 31) - sizeof(QByteArray::Data)) {
601  //QByteArray does not support that huge size anyway.
602  qWarning("qUncompress: Input data is corrupted");
603  return QByteArray();
604  }
605  QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + len));
606  if (!p) {
607  // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
608  qWarning("qUncompress: could not allocate enough memory to uncompress data");
609  return QByteArray();
610  }
611  d.take(); // realloc was successful
612  d.reset(p);
613  }
614  d->ref = 1;
615  d->alloc = d->size = len;
616  d->data = d->array;
617  d->array[len] = 0;
618 
619  return QByteArray(d.take(), 0, 0);
620 
621  case Z_MEM_ERROR:
622  qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
623  return QByteArray();
624 
625  case Z_BUF_ERROR:
626  len *= 2;
627  continue;
628 
629  case Z_DATA_ERROR:
630  qWarning("qUncompress: Z_DATA_ERROR: Input data is corrupted");
631  return QByteArray();
632  }
633  }
634 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
T * data() const
Returns the value of the pointer referenced by this object.
Data * d
Definition: qbytearray.h:386
T * take()
Returns the value of the pointer referenced by this object.
QBasicAtomicInt ref
Definition: qbytearray.h:139
QByteArray()
Constructs an empty byte array.
Definition: qbytearray.h:400
Q_CORE_EXPORT void * qRealloc(void *ptr, size_t size)
Definition: qmalloc.cpp:63
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon dest...
unsigned char uchar
Definition: qglobal.h:994
Q_CORE_EXPORT void qWarning(const char *,...)
unsigned long ulong
Definition: qglobal.h:997
void reset(T *other=0)
Deletes the existing object it is pointing to if any, and sets its pointer to other.
#define forever
This macro is provided for convenience for writing infinite loops.
Definition: qglobal.h:2452

◆ qUncompress() [2/2]

QByteArray qUncompress ( const QByteArray data)
related

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()

Definition at line 606 of file qbytearray.h.

607 { return qUncompress(reinterpret_cast<const uchar*>(data.constData()), data.size()); }
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
friend Q_CORE_EXPORT QByteArray qUncompress(const uchar *data, int nbytes)
Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data...
Definition: qbytearray.cpp:562

◆ qvsnprintf()

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

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::sprintf() instead.

See also
qsnprintf(), QString::sprintf()

Definition at line 78 of file qvsnprintf.cpp.

Referenced by backtrace_command(), qsnprintf(), and qstrncmp().

79 {
80  if (!str || !fmt)
81  return -1;
82 
83  QString buf;
84  buf.vsprintf(fmt, ap);
85 
86  QByteArray ba = buf.toLocal8Bit();
87 
88  if (n > 0) {
89  size_t blen = qMin(size_t(ba.length()), size_t(n - 1));
90  memcpy(str, ba.constData(), blen);
91  str[blen] = '\0'; // make sure str is always 0 terminated
92  }
93 
94  return ba.length();
95 }
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
The QString class provides a Unicode character string.
Definition: qstring.h:83
QString & vsprintf(const char *format, va_list ap)
Equivalent method to sprintf(), but takes a va_list ap instead a list of variable arguments...
Definition: qstring.cpp:5587
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
int length() const
Same as size().
Definition: qbytearray.h:356
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433

Properties

◆ d

Data* QByteArray::d
private

◆ shared_empty

QByteArray::Data QByteArray::shared_empty
staticprivate
Initial value:

Definition at line 385 of file qbytearray.h.

Referenced by append(), mid(), operator=(), prepend(), QByteArray(), qToLower(), resize(), and trimmed().

◆ shared_null

QByteArray::Data QByteArray::shared_null
staticprivate
Initial value:

Definition at line 384 of file qbytearray.h.

Referenced by append(), clear(), isNull(), mid(), operator=(), prepend(), QByteArray(), qToLower(), and resize().


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