Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QByteArray Class Reference

\inmodule QtCore More...

#include <qbytearray.h>

+ Inheritance diagram for QByteArray:
+ Collaboration diagram for QByteArray:

Classes

class  FromBase64Result
 \inmodule QtCore More...
 

Public Types

enum  Base64Option {
  Base64Encoding = 0 , Base64UrlEncoding = 1 , KeepTrailingEquals = 0 , OmitTrailingEquals = 2 ,
  IgnoreBase64DecodingErrors = 0 , AbortOnBase64DecodingErrors = 4
}
 
enum class  Base64DecodingStatus { Ok , IllegalInputLength , IllegalCharacter , IllegalPadding }
 
using DataPointer = QByteArrayData
 
typedef char * iterator
 This typedef provides an STL-style non-const iterator for QByteArray.
 
typedef const char * const_iterator
 This typedef provides an STL-style const iterator for QByteArray.
 
typedef iterator Iterator
 
typedef const_iterator ConstIterator
 
typedef std::reverse_iterator< iteratorreverse_iterator
 
typedef std::reverse_iterator< const_iteratorconst_reverse_iterator
 
typedef qsizetype size_type
 
typedef qptrdiff difference_type
 
typedef const char & const_reference
 
typedef char & reference
 
typedef char * pointer
 
typedef const char * const_pointer
 
typedef char value_type
 

Public Member Functions

constexpr QByteArray () noexcept
 Constructs an empty byte array.
 
 QByteArray (const char *, qsizetype size=-1)
 Constructs a byte array containing the first size bytes of array data.
 
 QByteArray (qsizetype size, char c)
 Constructs a byte array of size size with every byte set to ch.
 
 QByteArray (qsizetype size, Qt::Initialization)
 Constructs a byte array of size size with uninitialized contents.
 
 QByteArray (QByteArrayView v)
 
 QByteArray (const QByteArray &) noexcept
 Constructs a copy of other.
 
 ~QByteArray ()
 Destroys the byte array.
 
QByteArrayoperator= (const QByteArray &) noexcept
 Assigns other to this byte array and returns a reference to this byte array.
 
QByteArrayoperator= (const char *str)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Assigns str to this byte array.
 
 QByteArray (QByteArray &&other) noexcept=default
 Move-constructs a QByteArray instance, making it point at the same object that other was pointing to.
 
void swap (QByteArray &other) noexcept
 
bool isEmpty () const noexcept
 Returns true if the byte array has size 0; otherwise returns false.
 
void resize (qsizetype size)
 Sets the size of the byte array to size bytes.
 
void resize (qsizetype size, char c)
 
void resizeForOverwrite (qsizetype size)
 
QByteArrayfill (char c, qsizetype size=-1)
 Sets every byte in the byte array to ch.
 
qsizetype capacity () const
 Returns the maximum number of bytes that can be stored in the byte array without forcing a reallocation.
 
void reserve (qsizetype size)
 Attempts to allocate memory for at least size bytes.
 
void squeeze ()
 Releases any memory not required to store the array's data.
 
 operator const char * () const
 
 operator const void * () const
 
char * data ()
 \macro QT_NO_CAST_FROM_BYTEARRAY
 
const char * data () const noexcept
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const char * constData () const noexcept
 Returns a pointer to the const data stored in the byte array.
 
void detach ()
 
bool isDetached () const
 
bool isSharedWith (const QByteArray &other) const noexcept
 
void clear ()
 Clears the contents of the byte array and makes it null.
 
char at (qsizetype i) const
 Returns the byte at index position i in the byte array.
 
char operator[] (qsizetype i) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Same as at(i).
 
char & operator[] (qsizetype i)
 Returns the byte at index position i as a modifiable reference.
 
char front () const
 
char & front ()
 
char back () const
 
char & back ()
 
qsizetype indexOf (char c, qsizetype 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 start of the first occurrence of the byte ch in this byte array, searching forward from index position from.
 
qsizetype indexOf (QByteArrayView bv, qsizetype from=0) const
 
qsizetype lastIndexOf (char c, qsizetype 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 start of the last occurrence of byte ch in this byte array, searching backward from index position from.
 
qsizetype lastIndexOf (QByteArrayView bv) const
 
qsizetype lastIndexOf (QByteArrayView bv, qsizetype from) const
 
bool contains (char c) 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 byte ch; otherwise returns false.
 
bool contains (QByteArrayView bv) const
 
qsizetype count (char c) 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 number of occurrences of byte ch in the byte array.
 
qsizetype count (QByteArrayView bv) const
 
int compare (QByteArrayView a, Qt::CaseSensitivity cs=Qt::CaseSensitive) const noexcept
 
QByteArray left (qsizetype n) const &
 
QByteArray left (qsizetype n) &&
 
QByteArray right (qsizetype n) const &
 
QByteArray right (qsizetype n) &&
 
QByteArray mid (qsizetype index, qsizetype len=-1) const &
 
QByteArray mid (qsizetype index, qsizetype len=-1) &&
 
QByteArray first (qsizetype n) const &
 
QByteArray last (qsizetype n) const &
 
QByteArray sliced (qsizetype pos) const &
 
QByteArray sliced (qsizetype pos, qsizetype n) const &
 
QByteArray chopped (qsizetype len) const &
 
QByteArray first (qsizetype n) &&
 
QByteArray last (qsizetype n) &&
 
QByteArray sliced (qsizetype pos) &&
 
QByteArray sliced (qsizetype pos, qsizetype n) &&
 
QByteArray chopped (qsizetype len) &&
 
bool startsWith (QByteArrayView bv) const
 
bool startsWith (char c) 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 this byte array starts with byte ch; otherwise returns false.
 
bool endsWith (char c) 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 this byte array ends with byte ch; otherwise returns false.
 
bool endsWith (QByteArrayView bv) const
 
bool isUpper () const
 Returns true if this byte array is uppercase, that is, if it's identical to its toUpper() folding.
 
bool isLower () const
 Returns true if this byte array is lowercase, that is, if it's identical to its toLower() folding.
 
bool isValidUtf8 () const noexcept
 Returns true if this byte array contains valid UTF-8 encoded data, or false otherwise.
 
void truncate (qsizetype pos)
 Truncates the byte array at index position pos.
 
void chop (qsizetype n)
 Removes n bytes from the end of the byte array.
 
QByteArrayslice (qsizetype pos)
 
QByteArrayslice (qsizetype pos, qsizetype n)
 
QByteArray toLower () const &
 
QByteArray toLower () &&
 
QByteArray toUpper () const &
 
QByteArray toUpper () &&
 
QByteArray trimmed () const &
 
QByteArray trimmed () &&
 
QByteArray simplified () const &
 
QByteArray simplified () &&
 
QByteArray leftJustified (qsizetype width, char fill=' ', bool truncate=false) const
 Returns a byte array of size width that contains this byte array padded with the fill byte.
 
QByteArray rightJustified (qsizetype width, char fill=' ', bool truncate=false) const
 Returns a byte array of size width that contains the fill byte followed by this byte array.
 
QByteArrayprepend (char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Prepends the byte ch to this byte array.
 
QByteArrayprepend (qsizetype count, char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayprepend (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.Prepends the '\0'-terminated string str to this byte array.
 
QByteArrayprepend (const char *s, qsizetype len)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayprepend (const QByteArray &a)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Prepends ba to this byte array.
 
QByteArrayprepend (QByteArrayView a)
 Prepends the byte array view ba to this byte array and returns a reference to this byte array.
 
QByteArrayappend (char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the byte ch to this byte array.
 
QByteArrayappend (qsizetype count, char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayappend (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 '\0'-terminated string str to this byte array.
 
QByteArrayappend (const char *s, qsizetype len)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the first len bytes starting at str to this byte array and returns a reference to this byte array.
 
QByteArrayappend (const QByteArray &a)
 Appends the byte array ba onto the end of this byte array.
 
QByteArrayappend (QByteArrayView a)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends data to this byte array.
 
QByteArrayassign (QByteArrayView v)
 
QByteArrayassign (qsizetype n, char c)
 
template<typename InputIterator , if_input_iterator< InputIterator > = true>
QByteArrayassign (InputIterator first, InputIterator last)
 
QByteArrayinsert (qsizetype i, QByteArrayView data)
 
QByteArrayinsert (qsizetype i, const char *s)
 Inserts s at index position i and returns a reference to this byte array.
 
QByteArrayinsert (qsizetype i, const QByteArray &data)
 Inserts data at index position i and returns a reference to this byte array.
 
QByteArrayinsert (qsizetype i, qsizetype count, char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayinsert (qsizetype i, char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Inserts byte ch at index position i in the byte array.
 
QByteArrayinsert (qsizetype i, const char *s, qsizetype len)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayremove (qsizetype index, qsizetype len)
 Removes len bytes from the array, starting at index position pos, and returns a reference to the array.
 
QByteArrayremoveAt (qsizetype pos)
 
QByteArrayremoveFirst ()
 
QByteArrayremoveLast ()
 
template<typename Predicate >
QByteArrayremoveIf (Predicate pred)
 
QByteArrayreplace (qsizetype index, qsizetype len, const char *s, qsizetype 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 starting at position after.
 
QByteArrayreplace (qsizetype index, qsizetype len, QByteArrayView s)
 Replaces len bytes from index position pos with the byte array after, and returns a reference to this byte array.
 
QByteArrayreplace (char before, QByteArrayView 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 before with the byte array after.
 
QByteArrayreplace (const char *before, qsizetype bsize, const char *after, qsizetype 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 bsize bytes starting at before with the asize bytes starting at after.
 
QByteArrayreplace (QByteArrayView before, QByteArrayView after)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QByteArrayreplace (char before, 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 before with the byte after.
 
QByteArrayoperator+= (char c)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Appends the byte ch onto the end of this byte array and returns a reference to this byte array.
 
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 '\0'-terminated string str onto the end of this byte array and returns a reference to this byte array.
 
QByteArrayoperator+= (const QByteArray &a)
 Appends the byte array ba onto the end of this byte array and returns a reference to this byte array.
 
QByteArrayoperator+= (QByteArrayView a)
 
QList< QByteArraysplit (char sep) const
 Splits the byte array into subarrays wherever sep occurs, and returns the list of those arrays.
 
QByteArray repeated (qsizetype times) const
 
short toShort (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to a short using base base, which is ten by default.
 
ushort toUShort (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to an {unsigned short} using base base, which is ten by default.
 
int toInt (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to an int using base base, which is ten by default.
 
uint toUInt (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to an {unsigned int} using base base, which is ten by default.
 
long toLong (bool *ok=nullptr, int base=10) const
 
ulong toULong (bool *ok=nullptr, int base=10) const
 
qlonglong toLongLong (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to a {long long} using base base, which is ten by default.
 
qulonglong toULongLong (bool *ok=nullptr, int base=10) const
 Returns the byte array converted to an {unsigned long long} using base base, which is ten by default.
 
float toFloat (bool *ok=nullptr) const
 Returns the byte array converted to a float value.
 
double toDouble (bool *ok=nullptr) const
 Returns the byte array converted to a double value.
 
QByteArray toBase64 (Base64Options options=Base64Encoding) const
 
QByteArray toHex (char separator='\0') const
 Returns a hex encoded copy of the byte array.
 
QByteArray toPercentEncoding (const QByteArray &exclude=QByteArray(), const QByteArray &include=QByteArray(), char percent='%') const
 
QByteArray percentDecoded (char percent='%') const
 
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.
 
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.
 
QByteArraysetNum (int, int base=10)
 Represent the whole number n as text.
 
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.
 
QByteArraysetNum (long, 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.
 
QByteArraysetNum (ulong, 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.
 
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.
 
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.
 
QByteArraysetNum (float, char format='g', int precision=6)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Represent the floating-point number n as text.
 
QByteArraysetNum (double, char format='g', int precision=6)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Represent the floating-point number n as text.
 
QByteArraysetRawData (const char *a, qsizetype n)
 
iterator begin ()
 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first byte in the byte-array.
 
const_iterator begin () const noexcept
 
const_iterator cbegin () const noexcept
 
const_iterator constBegin () const noexcept
 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first byte in the byte-array.
 
iterator end ()
 Returns an \l{STL-style iterators}{STL-style iterator} pointing just after the last byte in the byte-array.
 
const_iterator end () const noexcept
 
const_iterator cend () const noexcept
 
const_iterator constEnd () const noexcept
 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just after the last byte in the byte-array.
 
reverse_iterator rbegin ()
 
reverse_iterator rend ()
 
const_reverse_iterator rbegin () const noexcept
 
const_reverse_iterator rend () const noexcept
 
const_reverse_iterator crbegin () const noexcept
 
const_reverse_iterator crend () const noexcept
 
void push_back (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(ch).
 
void push_back (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.Same as append(str).
 
void push_back (const QByteArray &a)
 This function is provided for STL compatibility.
 
void push_back (QByteArrayView a)
 
void push_front (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(ch).
 
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).
 
void push_front (const QByteArray &a)
 This function is provided for STL compatibility.
 
void push_front (QByteArrayView a)
 
void shrink_to_fit ()
 
iterator erase (const_iterator first, const_iterator last)
 
iterator erase (const_iterator it)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
std::string toStdString () const
 
qsizetype size () const noexcept
 Returns the number of bytes in this byte array.
 
qsizetype length () const noexcept
 Same as size().
 
bool isNull () const noexcept
 Returns true if this byte array is null; otherwise returns false.
 
const DataPointerdata_ptr () const
 
DataPointerdata_ptr ()
 
 QByteArray (DataPointer &&dd)
 

Static Public Member Functions

static QByteArray number (int, int base=10)
 Returns a byte-array representing the whole number n as text.
 
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.
 
static QByteArray number (long, 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.
 
static QByteArray number (ulong, 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.
 
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.
 
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.
 
static QByteArray number (double, char format='g', int precision=6)
 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 representing the floating-point number n as text.
 
static QByteArray fromRawData (const char *data, qsizetype size)
 Constructs a QByteArray that uses the first size bytes of the data array.
 
static FromBase64Result fromBase64Encoding (QByteArray &&base64, Base64Options options=Base64Encoding)
 
static FromBase64Result fromBase64Encoding (const QByteArray &base64, Base64Options options=Base64Encoding)
 
static QByteArray fromBase64 (const QByteArray &base64, Base64Options options=Base64Encoding)
 
static QByteArray fromHex (const QByteArray &hexEncoded)
 Returns a decoded copy of the hex encoded array hexEncoded.
 
static QByteArray fromPercentEncoding (const QByteArray &pctEncoded, char percent='%')
 
static constexpr qsizetype max_size () noexcept
 
static QByteArray fromStdString (const std::string &s)
 

Friends

class ::tst_QByteArray
 
class QString
 
bool comparesEqual (const QByteArray &lhs, const QByteArrayView &rhs) noexcept
 
Qt::strong_ordering compareThreeWay (const QByteArray &lhs, const QByteArrayView &rhs) noexcept
 
bool comparesEqual (const QByteArray &lhs, std::nullptr_t) noexcept
 
Qt::strong_ordering compareThreeWay (const QByteArray &lhs, std::nullptr_t) noexcept
 
Q_CORE_EXPORT bool comparesEqual (const QByteArray &lhs, const QChar &rhs) noexcept
 
Q_CORE_EXPORT Qt::strong_ordering compareThreeWay (const QByteArray &lhs, const QChar &rhs) noexcept
 
Q_CORE_EXPORT bool comparesEqual (const QByteArray &lhs, char16_t rhs) noexcept
 
Q_CORE_EXPORT Qt::strong_ordering compareThreeWay (const QByteArray &lhs, char16_t rhs) noexcept
 
Q_CORE_EXPORT QByteArray qUncompress (const uchar *data, qsizetype nbytes)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data.
 
template<typename T >
qsizetype erase (QByteArray &ba, const T &t)
 
template<typename Predicate >
qsizetype erase_if (QByteArray &ba, Predicate pred)
 

Related Symbols

(Note that these are not member symbols.)

char * qstrdup (const char *src)
 Returns a duplicate string.
 
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.
 
char * qstrncpy (char *dst, const char *src, size_t len)
 A safe strncpy() function.
 
size_t qstrlen (const char *str)
 A safe strlen() function.
 
size_t qstrnlen (const char *str, size_t maxlen)
 
int qstrcmp (const char *str1, const char *str2)
 A safe strcmp() function.
 
int qstrncmp (const char *str1, const char *str2, size_t len)
 A safe strncmp() function.
 
int qstricmp (const char *str1, const char *str2)
 A safe stricmp() function.
 
int qstrnicmp (const char *str1, const char *str2, size_t len)
 A safe strnicmp() function.
 
quint16 qChecksum (QByteArrayView data, Qt::ChecksumType standard)
 
QByteArray qCompress (const QByteArray &data, int compressionLevel)
 Compresses the data byte array and returns the compressed data in a new byte array.
 
QByteArray qCompress (const uchar *data, qsizetype nbytes, int compressionLevel)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Compresses the first nbytes of data at compression level compressionLevel and returns the compressed data in a new byte array.
 
QByteArray qUncompress (const QByteArray &data)
 Uncompresses the data byte array and returns a new byte array with the uncompressed data.
 
QByteArray qUncompress (const uchar *data, qsizetype nbytes)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data.
 
char * data ()
 \macro QT_NO_CAST_FROM_BYTEARRAY
 
QDataStreamoperator<< (QDataStream &out, const QByteArray &ba)
 Writes byte array ba to the stream out and returns a reference to the stream.
 
QDataStreamoperator>> (QDataStream &in, QByteArray &ba)
 Reads a byte array into ba from the stream in and returns a reference to the stream.
 
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.
 
QByteArray operator+ (const QByteArray &a1, const char *a2)
 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 '\0'-terminated string a2.
 
QByteArray operator+ (const QByteArray &a1, char a2)
 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 byte a2.
 
QByteArray operator+ (const char *a1, const QByteArray &a2)
 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 '\0'-terminated string a1 and byte array a2.
 
QByteArray operator+ (char a1, const QByteArray &a2)
 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 a1 and byte array a2.
 
 operator""_ba (const char *str, size_t size)
 \macro QByteArrayLiteral(ba)
 
template< typename T > qsizetype erase (QByteArray &ba, const T &t)
 
template< typename Predicate > qsizetype erase_if (QByteArray &ba, Predicate pred)
 
QT_BEGIN_NAMESPACE int qvsnprintf (char *str, size_t n, const char *fmt, va_list ap)
 A portable vsnprintf() function.
 
int qsnprintf (char *str, size_t n, const char *fmt,...)
 \target bytearray-qsnprintf
 

Detailed Description

\inmodule QtCore

The QByteArray class provides an array of bytes.

\reentrant

\compares strong \compareswith strong {const char *} QByteArrayView \endcompareswith \compareswith strong QChar char16_t QString QStringView QLatin1StringView \ QUtf8StringView When comparing with string types, the content is interpreted as utf-8. \endcompareswith

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 \l{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 understands its content as Unicode text (encoded using UTF-16) where QByteArray aims to avoid assumptions about the encoding or semantics of the bytes it stores (aside from a few legacy cases where it uses ASCII). 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":

Although the size() is 5, the byte array also maintains an extra '\0' byte 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 example for performance reasons, you don't want to take a deep copy of the data, use QByteArray::fromRawData() instead.)

Another approach is to set the size of the array using resize() and to initialize the data byte by 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:

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

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

To extract many bytes at a time, use first(), last(), or sliced().

A QByteArray can embed '\0' bytes. The size() function always returns the size of the whole array, including embedded '\0' bytes, but excluding the terminating '\0' added by QByteArray. For example:

QByteArray ba1("ca\0r\0t");
ba1.size(); // Returns 2.
ba1.constData(); // Returns "ca" with terminating \0.
QByteArray ba2("ca\0r\0t", 3);
ba2.size(); // Returns 3.
ba2.constData(); // Returns "ca\0" with terminating \0.
QByteArray ba3("ca\0r\0t", 4);
ba3.size(); // Returns 4.
ba3.constData(); // Returns "ca\0r" with terminating \0.
const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
ba4.size(); // Returns 6.
ba4.constData(); // Returns "ca\0r\0t" without terminating \0.

If you want to obtain the length of the data up to and excluding the first '\0' byte, 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 bytes, 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 \l{fromRawData()}{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:

In the above example the replace() function's first two arguments are the position from which to start replacing and the number of bytes that should be replaced.

When data-modifying functions increase the size of the array, they may lead to reallocation of memory for the QByteArray object. When this happens, QByteArray expands by more than it immediately needs so as to have space for further expansion without reallocation until the size of the array has greatly increased.

The insert(), remove() and, when replacing a sub-array with one of different size, replace() functions can be slow (\l{linear time}) for large arrays, because they require moving many bytes in the array by at least one position in memory.

If you are building a QByteArray gradually and know in advance approximately how many bytes the QByteArray will contain, you can call reserve(), asking QByteArray to preallocate a certain amount of memory. You can also call capacity() to find out how much memory the QByteArray actually has allocated.

Note that using non-const operators and functions can cause QByteArray to do a deep copy of the data, due to \l{implicit sharing}.

QByteArray provides \l{STL-style iterators} (QByteArray::const_iterator and QByteArray::iterator). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.

Note
Iterators and references to individual QByteArray elements are subject to stability issues. They are often invalidated when a QByteArray-modifying operation (e.g. insert() or remove()) is called. When stability and iterator-like functionality is required, you should use indexes instead of iterators as they are not tied to QByteArray's internal state and thus do not get invalidated.
Iterators over a QByteArray, and references to individual bytes within one, cannot be relied on to remain valid when any non-const method of the QByteArray is called. Accessing such an iterator or reference after the call to a non-const method leads to undefined behavior. When stability for iterator-like functionality is required, you should use indexes instead of iterators as they are not tied to QByteArray's internal state and thus do not get invalidated.

If you want to find all occurrences of a particular byte or sequence of bytes 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 byte sequence if they find it; otherwise, they return -1. For example, here's a typical loop that finds all occurrences of a particular string:

If you simply want to check whether a QByteArray contains a particular byte sequence, use contains(). If you want to find out how many times a particular byte sequence 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.

\l{QByteArray}s 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 bytes 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:

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

Definition at line 56 of file qbytearray.h.

Member Typedef Documentation

◆ const_iterator

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

See also
QByteArray::const_reverse_iterator, QByteArray::iterator

Definition at line 438 of file qbytearray.h.

◆ const_pointer

Definition at line 464 of file qbytearray.h.

◆ const_reference

Definition at line 461 of file qbytearray.h.

◆ const_reverse_iterator

Since
5.6

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

See also
QByteArray::reverse_iterator, QByteArray::const_iterator

Definition at line 442 of file qbytearray.h.

◆ ConstIterator

Definition at line 440 of file qbytearray.h.

◆ DataPointer

Definition at line 59 of file qbytearray.h.

◆ difference_type

Definition at line 460 of file qbytearray.h.

◆ iterator

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

See also
QByteArray::reverse_iterator, QByteArray::const_iterator

Definition at line 437 of file qbytearray.h.

◆ Iterator

Definition at line 439 of file qbytearray.h.

◆ pointer

Definition at line 463 of file qbytearray.h.

◆ reference

Definition at line 462 of file qbytearray.h.

◆ reverse_iterator

Since
5.6

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

See also
QByteArray::const_reverse_iterator, QByteArray::iterator

Definition at line 441 of file qbytearray.h.

◆ size_type

Definition at line 459 of file qbytearray.h.

◆ value_type

Definition at line 465 of file qbytearray.h.

Member Enumeration Documentation

◆ Base64DecodingStatus

Enumerator
Ok 
IllegalInputLength 
IllegalCharacter 
IllegalPadding 

Definition at line 84 of file qbytearray.h.

◆ Base64Option

Since
5.2

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

\value Base64Encoding (default) The regular Base64 alphabet, called simply "base64" \value Base64UrlEncoding An alternate alphabet, called "base64url", which replaces two characters in the alphabet to be more friendly to URLs. \value KeepTrailingEquals (default) Keeps the trailing padding equal signs at the end of the encoded data, so the data is always a size multiple of four. \value OmitTrailingEquals Omits adding the padding equal signs at the end of the encoded data. \value IgnoreBase64DecodingErrors When decoding Base64-encoded data, ignores errors in the input; invalid characters are simply skipped. This enum value has been added in Qt 5.15. \value AbortOnBase64DecodingErrors When decoding Base64-encoded data, stops at the first decoding error. This enum value has been added in Qt 5.15.

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

Enumerator
Base64Encoding 
Base64UrlEncoding 
KeepTrailingEquals 
OmitTrailingEquals 
IgnoreBase64DecodingErrors 
AbortOnBase64DecodingErrors 

Definition at line 72 of file qbytearray.h.

Constructor & Destructor Documentation

◆ QByteArray() [1/8]

constexpr QByteArray::QByteArray ( )
inlineconstexprnoexcept

Constructs an empty byte array.

See also
isEmpty()

Definition at line 597 of file qbytearray.h.

Referenced by fromBase64(), fromStdString(), repeated(), toHex(), and toPercentEncoding().

+ Here is the caller graph for this function:

◆ QByteArray() [2/8]

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

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

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

If size is negative, data is assumed to point to a '\0'-terminated string and its length is determined dynamically.

QByteArray makes a deep copy of the string data.

See also
fromRawData()

Definition at line 1814 of file qbytearray.cpp.

References QArrayDataPointer< T >::data(), QArrayDataPointer< T >::fromRawData(), Q_CHECK_PTR(), and qstrlen().

+ Here is the call graph for this function:

◆ QByteArray() [3/8]

QByteArray::QByteArray ( qsizetype size,
char ch )

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

See also
fill()

Definition at line 1838 of file qbytearray.cpp.

References ch, QArrayDataPointer< T >::data(), QArrayDataPointer< T >::fromRawData(), and Q_CHECK_PTR().

+ Here is the call graph for this function:

◆ QByteArray() [4/8]

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

Constructs a byte array of size size with uninitialized contents.

Definition at line 1854 of file qbytearray.cpp.

References QArrayDataPointer< T >::data(), QArrayDataPointer< T >::fromRawData(), and Q_CHECK_PTR().

+ Here is the call graph for this function:

◆ QByteArray() [5/8]

QByteArray::QByteArray ( QByteArrayView v)
inlineexplicit

Definition at line 95 of file qbytearray.h.

◆ QByteArray() [6/8]

QByteArray::QByteArray ( const QByteArray & other)
inlinenoexcept

Constructs a copy of other.

This operation takes \l{constant time}, because QByteArray is \l{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 \l{linear time}.

See also
operator=()

Definition at line 629 of file qbytearray.h.

◆ ~QByteArray()

QByteArray::~QByteArray ( )
inline

Destroys the byte array.

Definition at line 598 of file qbytearray.h.

◆ QByteArray() [7/8]

QByteArray::QByteArray ( QByteArray && other)
inlinedefaultnoexcept

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

Since
5.2

◆ QByteArray() [8/8]

QByteArray::QByteArray ( DataPointer && dd)
inlineexplicit

Definition at line 508 of file qbytearray.h.

Member Function Documentation

◆ append() [1/6]

QByteArray & QByteArray::append ( char c)

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

Definition at line 2143 of file qbytearray.cpp.

References ch, QArrayDataPointer< T >::data(), QArrayDataPointer< T >::detachAndGrow(), QArrayData::GrowsAtEnd, and QArrayDataPointer< T >::size.

Referenced by QOpenGLEngineSharedShaders::QOpenGLEngineSharedShaders(), QCborStreamReader::addData(), QQuick3DParticleInstanceTable::addInstance(), QSSGStageGeneratorBase::addShaderConstantBufferItemMap(), QSSGStageGeneratorBase::addShaderItemMap(), QSSGStageGeneratorBase::addShaderPass2Marker(), append(), QSSGStageGeneratorBase::append(), QSSGStageGeneratorBase::appendShaderCode(), appendVariant(), QCommandApdu::build(), QSSGStageGeneratorBase::buildShaderSourcePass1(), checkLightxml(), QmlLsp::codeActionHandler(), QSslContext::createSsl(), QMimerSQLResult::data(), QNetworkReplyWasmImplPrivate::dataReceived(), HPack::HuffmanDecoder::decodeStream(), QMYSQLResult::exec(), QSSGRenderEffect::finalizeShaders(), QOpenGLEngineSharedShaders::findProgramInCache(), QTest::formatResult(), QSSGMesh::Mesh::fromAssetData(), generateFragmentShader(), generateMainLightCalculation(), QWaylandMimeHelper::getByteArray(), QHttpNetworkReplyPrivate::getChunkSize(), QQuick3DFileInstancing::loadFromXmlFile(), QOpenGLDebugLogger::logMessage(), Preprocessor::macroExpandIdentifier(), QIBaseDriver::open(), QSSGStageGeneratorBase::operator<<(), QQmlError::operator<<(), parseSdpRecord(), parseTzAbbreviations(), QTlsPrivate::TlsKeyBase::pemFromDer(), QHttpNetworkConnectionChannel::pipelineInto(), prefixMessage(), prepareCustomShader(), QDtlsPrivateOpenSSL::pskClientCallback(), QOpenGLDebugLogger::pushGroup(), qEncodeHmacMd5(), qt_socks5_set_host_name_and_port(), read_xpm_body(), QHttpNetworkReplyPrivate::readHeader(), QJpegHandlerPrivate::readJpegHeader(), QHttpNetworkReplyPrivate::readStatus(), QSSGShaderUtils::resolveShader(), QHttpProtocolHandler::sendRequest(), setNum(), setNum(), trace::toByteArray(), trace::toByteArray(), trace::toByteArray(), trace::toByteArray(), trace::toByteArrayFromArray(), trace::toByteArrayFromCString(), trace::toByteArrayFromEnum(), trace::toByteArrayFromFlags(), QQuick3DEffect::updateSpatialNode(), QSSGShaderDefaultMaterialKey::StringVisitor::visit(), TestHTTPServer::wait(), and QFFmpeg::AudioSourceIO::writeData().

+ Here is the call graph for this function:

◆ append() [2/6]

QByteArray & QByteArray::append ( 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 '\0'-terminated string str to this byte array.

Definition at line 293 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ append() [3/6]

QByteArray & QByteArray::append ( const char * str,
qsizetype len )
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 first len bytes starting at str to this byte array and returns a reference to this byte array.

The bytes appended may include '\0' bytes.

If len is negative, str will be assumed to be a '\0'-terminated string and the length to be copied will be determined automatically using qstrlen().

If len is zero or str is null, nothing is appended to the byte array. Ensure that len is not longer than str.

Definition at line 295 of file qbytearray.h.

References append(), and qstrlen().

+ Here is the call graph for this function:

◆ append() [4/6]

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 \l{implicitly shared} class. Consequently, if you append to an empty byte array, then the byte array will just share the data held in ba. In this case, no copying of data is done, taking \l{constant time}. If a shared instance is modified, it will be copied (copy-on-write), taking \l{linear time}.

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

The append() function is typically very fast (\l{constant time}), because QByteArray preallocates extra space at the end of the data, so it can grow without reallocating the entire array each time.

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

Definition at line 2081 of file qbytearray.cpp.

References append(), assign(), ba, QArrayDataPointer< T >::isMutable(), isNull(), operator=(), Q_UNLIKELY, and size().

+ Here is the call graph for this function:

◆ append() [5/6]

QByteArray & QByteArray::append ( QByteArrayView a)
inline

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

Definition at line 298 of file qbytearray.h.

References insert().

+ Here is the call graph for this function:

◆ append() [6/6]

QByteArray & QByteArray::append ( qsizetype count,
char ch )
inline

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

Since
5.7

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

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

Definition at line 656 of file qbytearray.h.

References ch, and insert().

+ Here is the call graph for this function:

◆ assign() [1/3]

template<typename InputIterator , if_input_iterator< InputIterator > = true>
QByteArray & QByteArray::assign ( InputIterator first,
InputIterator last )
inline

Definition at line 308 of file qbytearray.h.

References assign(), d, and data().

+ Here is the call graph for this function:

◆ assign() [2/3]

QByteArray & QByteArray::assign ( QByteArrayView v)
Since
6.6

Replaces the contents of this byte array with a copy of v and returns a reference to this byte array.

The size of this byte array will be equal to the size of v.

This function only allocates memory if the size of v exceeds the capacity of this byte array or this byte array is shared.

Definition at line 2201 of file qbytearray.cpp.

References QArrayDataPointer< T >::begin(), capacity(), QArrayDataPointer< T >::data(), QArrayDataPointer< T >::freeSpaceAtBegin(), isDetached(), QArrayDataPointer< T >::setBegin(), size(), and QArrayDataPointer< T >::size.

Referenced by append(), assign(), operator=(), and QSSGShaderCustomMaterialAdapter::prepareCustomShader().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ assign() [3/3]

QByteArray & QByteArray::assign ( qsizetype n,
char c )
inline
Since
6.6

Replaces the contents of this byte array with n copies of c and returns a reference to this byte array.

The size of this byte array will be equal to n, which has to be non-negative.

This function will only allocate memory if n exceeds the capacity of this byte array or this byte array is shared.

See also
fill()

Definition at line 302 of file qbytearray.h.

References fill(), and Q_ASSERT.

+ Here is the call graph for this function:

◆ at()

char QByteArray::at ( qsizetype i) const
inline

◆ back() [1/2]

char & QByteArray::back ( )
inline
Since
5.10

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

This function is provided for STL compatibility.

Warning
Calling this function on an empty byte array constitutes undefined behavior.
See also
front(), at(), operator[]()

Definition at line 655 of file qbytearray.h.

References operator[]().

+ Here is the call graph for this function:

◆ back() [2/2]

char QByteArray::back ( ) const
inline
Since
5.10

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

This function is provided for STL compatibility.

Warning
Calling this function on an empty byte array constitutes undefined behavior.
See also
front(), at(), operator[]()

Definition at line 136 of file qbytearray.h.

References at.

Referenced by QTlsPrivate::Q_GLOBAL_STATIC_WITH_ARGS(), and QAsn1Element::toDateTime().

+ Here is the caller graph for this function:

◆ begin() [1/2]

QByteArray::iterator QByteArray::begin ( )
inline

Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first byte in the byte-array.

! [iterator-invalidation-func-desc]

Warning
The returned iterator is invalidated on detachment or when the QByteArray is modified. ! [iterator-invalidation-func-desc]
\sa constBegin(), end()

Definition at line 443 of file qbytearray.h.

Referenced by QConcatenable< QByteArray >::appendTo(), erase(), isLower(), isUpper(), QTimeZonePrivate::isValidId(), and remove().

+ Here is the caller graph for this function:

◆ begin() [2/2]

const_iterator QByteArray::begin ( ) const
inlinenoexcept

Definition at line 444 of file qbytearray.h.

References d.

◆ capacity()

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

Note
a statically allocated byte array will report a capacity of 0, even if it's not empty.
The free space position in the allocated memory block is undefined. In other words, one should not assume that the free memory is always located after the initialized elements.
See also
reserve(), squeeze()

Definition at line 632 of file qbytearray.h.

References d.

Referenced by assign(), QOCIResultPrivate::bindValue(), QOCICols::execBatch(), reserve(), resize(), and squeeze().

+ Here is the caller graph for this function:

◆ cbegin()

QByteArray::const_iterator QByteArray::cbegin ( ) const
inlinenoexcept
Since
5.0

Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first byte in the byte-array.

iterator-invalidation-func-desc

See also
begin(), cend()

Definition at line 445 of file qbytearray.h.

References begin().

Referenced by QPasswordDigestor::deriveKeyPbkdf2(), and erase().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cend()

QByteArray::const_iterator QByteArray::cend ( ) const
inlinenoexcept
Since
5.0

Returns a const \l{STL-style iterators}{STL-style iterator} pointing just after the last byte in the byte-array.

iterator-invalidation-func-desc

See also
cbegin(), end()

Definition at line 449 of file qbytearray.h.

◆ chop()

void QByteArray::chop ( qsizetype 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(), first()

Definition at line 1726 of file qbytearray.cpp.

References resize().

Referenced by Moc::checkProperties(), QmlLsp::codeActionHandler(), QtWaylandClient::convertData(), QFileSystemEngine::createDirectory(), Moc::parseMocInclude(), QMimeData::setData(), toString(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ chopped() [1/2]

QByteArray QByteArray::chopped ( qsizetype len) &&
inline

Definition at line 219 of file qbytearray.h.

◆ chopped() [2/2]

QByteArray QByteArray::chopped ( qsizetype len) const &
inline

Definition at line 204 of file qbytearray.h.

◆ clear()

void QByteArray::clear ( )

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

See also
resize(), isNull()

Definition at line 3330 of file qbytearray.cpp.

References d.

Referenced by QBuffer::QBuffer(), QProgressDialogPrivate::_q_disconnectOnClose(), QSSGStageGeneratorBase::begin(), QMessageBoxPrivate::buttonClicked(), QSctpSocketPrivate::canReadNotification(), QNetworkDatagram::clear(), QNdefRecord::clear(), QNmeaSatelliteInfoUpdate::clear(), QQuick3DParticleInstanceTable::clear(), QTlsPrivate::TlsKeyGeneric::clear(), QNetworkRequestFactory::clearBearerToken(), QPdfDocument::close(), QGuiApplicationPrivate::createPlatformIntegration(), QSslContext::createSsl(), debugBinaryString(), QDtlsPrivateOpenSSL::decryptDatagram(), QHttpNetworkReplyPrivate::getChunkSize(), QNfcTagType4NdefFsm::getMessage(), QTlsPrivate::TlsCryptographOpenSSL::init(), QQmlPreviewFileLoader::load(), operator>>(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QHttpNetworkConnectionChannel::pipelineFlush(), QSGMaterialShaderPrivate::prepare(), processSentence(), QDtlsPrivateOpenSSL::pskClientCallback(), QPulseAudioSource::read(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkReplyPrivate::readStatus(), QNetworkAccessCache::removeEntry(), QNetworkReplyHttpImplPrivate::replyDownloadMetaData(), QNonContiguousByteDeviceThreadForwardImpl::reset(), QSSGParticleRenderer::rhiPrepareRenderable(), QBuffer::setBuffer(), setNum(), setNum(), setRawData(), QAndroidAudioSource::start(), QDtlsClientVerifierOpenSSL::verifyClient(), TestHTTPServer::wait(), and writeDib().

+ Here is the caller graph for this function:

◆ compare()

int QByteArray::compare ( QByteArrayView bv,
Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
inlinenoexcept
Since
6.0

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

See also
operator==, {Character Case}

Definition at line 664 of file qbytearray.h.

References Qt::CaseSensitive, QtPrivate::compareMemory(), QString::cs, and qstrnicmp().

Referenced by QEglFSIntegration::nativeResourceFunctionForContext(), and QFile::rename().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ constBegin()

QByteArray::const_iterator QByteArray::constBegin ( ) const
inlinenoexcept

Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first byte in the byte-array.

iterator-invalidation-func-desc

See also
begin(), constEnd()

Definition at line 446 of file qbytearray.h.

References begin().

Referenced by normalizeType().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ constData()

const char * QByteArray::constData ( ) const
inlinenoexcept

Returns a pointer to the const 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.

pointer-invalidation-desc

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 124 of file qbytearray.h.

Referenced by QCborValue::QCborValue(), QEglFSKmsScreen::QEglFSKmsScreen(), QGstreamerVideoOverlay::QGstreamerVideoOverlay(), QMimeMagicRule::QMimeMagicRule(), QPpdPrintDevice::QPpdPrintDevice(), QQnxIntegration::QQnxIntegration(), QQnxWindow::QQnxWindow(), QResponseApdu::QResponseApdu(), QXcbBasicConnection::QXcbBasicConnection(), QAbstractSocketPrivate::_q_connectToNextAddress(), addFunction(), QtAndroidQuickViewEmbedding::addRootObjectSignalListener(), QCborStreamWriter::append(), appendVariant(), applyMetaDataToTagSetter(), RingBuffer::availableData(), QSctpSocketPrivate::canReadNotification(), QWindowsFontEngine::capHeight(), Moc::checkProperties(), Moc::checkSuperClasses(), childKeysOrGroups(), QQmlPropertyCache::className(), QXcbConnection::clientLeader(), QCupsPrintEnginePrivate::closePrintDevice(), QSGCompressedTexture::commitTextureOperations(), commonCopyEvent(), QRhiGles2::compileShader(), QQmlLoggingCategory::componentComplete(), computeFaceIndex(), QLowEnergyControllerPrivateWinRT::connectToDevice(), QAbstractSocket::connectToHost(), QUtf32::convertFromUnicode(), QXcbWindow::create(), QD3D11Buffer::create(), QD3D11RenderBuffer::create(), QD3D11Texture::create(), QD3D11GraphicsPipeline::create(), QD3D11ComputePipeline::create(), QGles2Buffer::create(), QGles2RenderBuffer::create(), QGles2Texture::create(), QGles2TextureRenderTarget::create(), QGles2GraphicsPipeline::create(), QMetalBuffer::create(), QMetalRenderBuffer::create(), QMetalTexture::create(), QMetalComputePipeline::create(), QSSGMesh::Mesh::createLightmapUVChannel(), QRhiMetalData::createMSLShaderFunction(), QSslContext::createSsl(), QMetalGraphicsPipeline::createTessellationPipelines(), QMetalGraphicsPipeline::createVertexFragmentPipeline(), QRingChunk::data(), QQmlFile::data(), QtWaylandClient::QWaylandDataSource::data_source_send(), QQuickScriptActionPrivate::debugAction(), QAnimationGroupJob::debugChildren(), QRhiD3D11::debugMarkMsg(), QRhiMetal::debugMarkMsg(), QRhiVulkan::debugMarkMsg(), QQuickAnimationPropertyUpdater::debugUpdater(), QTest::defaultEventDelay(), QTest::defaultKeyDelay(), QTest::defaultMouseDelay(), QAVFCameraBase::device(), QObject::disconnect(), QNetworkReplyWasmImplPrivate::doSendRequest(), QPainter::drawText(), QPainter::drawText(), QPainter::drawText(), QPainter::drawText(), QPdfEnginePrivate::drawTextItem(), dumpAttributeVariant(), QV4::Moth::dumpBytecode(), dumpErrorInformation(), QObject::dumpObjectInfo(), QQmlNativeDebugServiceImpl::emitAsynchronousMessageToClient(), encodeEntity(), encodeFileName(), QRhiMetal::enqueueSubresUpload(), escapedString(), QQmlCustomParser::evaluateEnum(), QWidget::event(), QDB2Result::exec(), QMimerSQLResult::exec(), QMYSQLResult::exec(), QODBCResult::exec(), QSQLiteResult::exec(), QPSQLDriverPrivate::exec(), QOCICols::execBatch(), QuickTestResult::expectFail(), QuickTestResult::expectFailContinue(), extractServiceData(), QQuickDialogTestUtils::DialogTestHelper< DialogType, QuickDialogType >::failureMessage(), QQuickVisualTestUtils::QQuickApplicationHelper::failureMessage(), QAbstractSocketPrivate::fetchConnectionParameters(), QNativeSocketEnginePrivate::fetchConnectionParameters(), FontProvider::fetchFont(), QZipReader::fileData(), QGtk3Interface::fileIcon(), findPatternUnloaded(), QOpenGLEngineSharedShaders::findProgramInCache(), QMinimalBackingStore::flush(), QPSQLDriver::formatValue(), QJsonDocument::fromJson(), QHostInfoAgent::fromName(), Generator::generateCode(), generateInterfaceXml(), QWindowsFontEngine::getCMap(), QTextureFileData::getDataView(), QFileSystemEngine::getLinkTarget(), QXcbScreen::getName(), QLibProxyWrapper::getProxies(), QFileSystemEngine::getRawLinkPath(), getRhiImplementation(), QNearFieldTargetPrivateImpl::getTagTechnology(), QQnxClipboard::MimeData::hasFormat(), QNonContiguousByteDeviceThreadForwardImpl::haveDataSlot(), QWaylandCompositorPrivate::init(), QGeoSatelliteInfoSourceGypsy::init(), QBasicPlatformVulkanInstance::initInstance(), QAbstractSocketPrivate::initSocketLayer(), InstanceModel::instanceData(), QtAndroidQuickViewEmbedding::SignalHelper::invokeListener(), QDBusUtil::isValidSignature(), QDBusUtil::isValidSingleSignature(), QIODevicePrivate::isWriteChunkCached(), QXcbKeyboard::keymapFromCore(), QRhiGles2::linkProgram(), QSvgIOHandlerPrivate::load(), QFontEngine::loadKerningPairs(), QHostInfoAgent::lookup(), main(), QMemoryVideoBuffer::map(), QV4DebugServiceImpl::messageReceived(), QQmlNativeDebugServiceImpl::messageReceived(), QPdfDocument::metaData(), QV4::GlobalFunctions::method_parseFloat(), QXcbMime::mimeAtomToString(), QMimeDatabasePrivate::mimeTypeForFile(), nameToOSType(), QWindowsDirect2DNativeInterface::nativeResourceForBackingStore(), QWindowsGdiNativeInterface::nativeResourceForBackingStore(), QWindowsNativeInterface::nativeResourceForContext(), QWindowsNativeInterface::nativeResourceForScreen(), QWindowsNativeInterface::nativeResourceForWindow(), QtWayland::DataDeviceManager::offerFromCompositorToClient(), QDB2Driver::open(), QMimerSQLDriver::open(), QMYSQLDriver::open(), QHaikuServices::openDocument(), openFramebufferDevice(), operator<<(), QQmlError::operator<<(), RCCResourceLibrary::output(), QEdidParser::parse(), QDateTimeParser::parse(), Preprocessor::parseDefineArguments(), Moc::parseFunction(), Moc::parseMaybeFunction(), Moc::parsePluginData(), Moc::parsePropertyAttributes(), QRhiD3D11::pipelineCacheData(), QRhiGles2::pipelineCacheData(), QRhiMetal::pipelineCacheData(), QSSGParticleBuffer::pointer(), QByteDataBuffer::popFront(), QXcbXSettingsPrivate::populateSettings(), QSGMaterialShaderPrivate::prepare(), QRhiVulkan::prepareUploadSubres(), printRenderPassDetails(), Scanner::printUsage(), Scanner::process(), QFontEngine::processHheaTable(), QDtlsPrivateOpenSSL::pskClientCallback(), QPcscSlotName::ptr(), QOpenGLDebugLogger::pushGroup(), qEncodeNtlmv2Response(), QTest::qPrintDataTags(), QTest::qPrintMessage(), qSaveQmlJSUnitAsCpp(), QSGBatchRenderer::qsg_dumpShadowRoots(), QSGBatchRenderer::qsg_dumpShadowRoots(), qt_convert_to_latin1(), qtValue(), qvsnprintf(), qWaitForSignal(), QAstcHandler::read(), QPkmHandler::read(), QPulseAudioSource::read(), QWebpHandler::read(), read32bitIcon(), QHttpPartPrivate::readData(), QAbstractSocketPrivate::readFromSocket(), QSSGMesh::MeshInternal::readMeshData(), QNonContiguousByteDeviceByteArrayImpl::readPointer(), QRestReply::readText(), QtQuickControls2Plugin::registerTypes(), QDBusAdaptorConnector::relay(), QFileSystemEngine::removeDirectory(), QVideoWindowPrivate::render(), QFontconfigDatabase::resolveFontFamilyAlias(), QD3D11CommandBuffer::retainData(), QGles2CommandBuffer::retainData(), QQnxClipboard::MimeData::retrieveData(), QHeaderDataProxyModel::roleNames(), QQmlJSShadowCheck::run(), QQmlJSCodeGenerator::run(), QQmlJSBasicBlocks::run(), QQmlJSTypePropagator::run(), QSSGLightmapUVGenerator::run(), runMoc(), runUic(), QToolBarAreaLayout::saveState(), searchIncludePaths(), QV4DebugServiceImpl::send(), HciManager::sendCommand(), QPSQLDriverPrivate::sendQuery(), set_text(), QDBusAbstractAdaptor::setAutoRelaySignals(), QTimeLinePrivate::setCurrentTime(), QGstreamerMediaPlayer::setMedia(), QRhiGles2::setPipelineCacheData(), QRhiMetal::setPipelineCacheData(), QWaylandSurface::setRole(), QWasmAudioOutput::setSource(), QTextBrowserPrivate::setSource(), QXcbWindow::setWindowIconText(), QHaikuWindow::setWindowTitle(), QXcbWindow::setWindowTitle(), QGstreamerAudioDecoder::start(), QSSGRhiContextStats::stop(), QV4::RuntimeHelpers::stringToNumber(), QWindowsFontDatabaseBase::EmbeddedFont::tableDirectoryEntry(), QQuickWheelHandlerPrivate::targetMetaProperty(), QQuickCanvasItem::toDataURL(), QIcc::toIccProfile(), ClassDef::toJson(), QSSGMesh::MeshInternal::Subset::toMeshSubset(), QTest::toString(), QTest::toString(), QTest::toString(), QTest::Internal::toString(), QQuickPropertyAction::transition(), QLockFilePrivate::tryLock_sys(), QtQuickControls2Plugin::unregisterTypes(), QXcbClipboardTransaction::updateIncrementalProperty(), uuidToByteArray(), QQmlObjectModel::variantValue(), QQnxScreen::windowGroupName(), wrapInFunction(), QICNSHandler::write(), QTiffHandler::write(), QWebpHandler::write(), write_icc_profile(), writeAttribute(), QLowEnergyControllerPrivateAndroid::writeCharacteristic(), RCCFileInfo::writeDataBlob(), QDtlsPrivateOpenSSL::writeDatagramEncrypted(), QLowEnergyControllerPrivateAndroid::writeDescriptor(), QPNGImageWriter::writeImage(), writeInstanceTable(), QSSGMesh::MeshInternal::writeMeshData(), QSctpSocketPrivate::writeToSocket(), QWaylandXdgShellPrivate::xdg_wm_base_get_xdg_surface(), and QtWaylandClient::QWaylandPrimarySelectionSourceV1::zwp_primary_selection_source_v1_send().

◆ constEnd()

QByteArray::const_iterator QByteArray::constEnd ( ) const
inlinenoexcept

Returns a const \l{STL-style iterators}{STL-style iterator} pointing just after the last byte in the byte-array.

iterator-invalidation-func-desc

See also
constBegin(), end()

Definition at line 450 of file qbytearray.h.

Referenced by normalizeType().

+ Here is the caller graph for this function:

◆ contains() [1/2]

bool QByteArray::contains ( char c) 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 byte ch; otherwise returns false.

Definition at line 660 of file qbytearray.h.

References indexOf().

Referenced by QHttpNetworkConnectionChannel::detectPipeliningSupport(), QQuickDesignerSupportProperties::isPropertyBlackListed(), matches(), EnumDef::qualifiedType(), QHttpNetworkReplyPrivate::readHeader(), and toPercentEncoding().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ contains() [2/2]

bool QByteArray::contains ( QByteArrayView bv) const
inline
Since
6.0

Returns true if this byte array contains an occurrence of the sequence of bytes viewed by bv; otherwise returns false.

See also
indexOf(), count()

Definition at line 662 of file qbytearray.h.

References indexOf().

+ Here is the call graph for this function:

◆ count() [1/2]

qsizetype QByteArray::count ( char ch) 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 number of occurrences of byte ch in the byte array.

See also
contains(), indexOf()

Definition at line 2908 of file qbytearray.cpp.

References ch, and countCharHelper().

Referenced by QQuickDesignerSupportProperties::isPropertyBlackListed(), and QWizard::setPage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ count() [2/2]

qsizetype QByteArray::count ( QByteArrayView bv) const
inline
Since
6.0

Returns the number of (potentially overlapping) occurrences of the sequence of bytes viewed by bv in this byte array.

See also
contains(), indexOf()

Definition at line 154 of file qbytearray.h.

References QtPrivate::count(), and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ crbegin()

QByteArray::const_reverse_iterator QByteArray::crbegin ( ) const
inlinenoexcept
Since
5.6

Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first byte in the byte-array, in reverse order.

iterator-invalidation-func-desc

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

Definition at line 455 of file qbytearray.h.

◆ crend()

QByteArray::const_reverse_iterator QByteArray::crend ( ) const
inlinenoexcept
Since
5.6

Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing just after the last byte in the byte-array, in reverse order.

iterator-invalidation-func-desc

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

Definition at line 456 of file qbytearray.h.

◆ data() [1/2]

char * QByteArray::data ( )
inline

\macro QT_NO_CAST_FROM_BYTEARRAY

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

See also
QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII

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 you can access following the returned pointer is size() + 1, including the '\0' terminator.

Example:

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

pointer-invalidation-desc

For read-only access, constData() is faster because it never causes a \l{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";
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 611 of file qbytearray.h.

References d, detach(), and Q_ASSERT.

Referenced by QBitArray::QBitArray(), QQnxIntegration::QQnxIntegration(), QQnxWindow::QQnxWindow(), QSSGMeshBVHBuilder::QSSGMeshBVHBuilder(), QXcbSessionManager::QXcbSessionManager(), _q_lower(), _q_upper(), QPdfEnginePrivate::addImage(), assign(), QSocks5PasswordAuthenticator::beginAuthenticate(), QOCIResultPrivate::bindValue(), QSslContext::cacheSession(), QSctpSocketPrivate::canReadNotification(), QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(), QTlsPrivate::X509CertificateOpenSSL::certificatesFromPem(), QODBCDriverPrivate::checkUnicode(), childKeysOrGroups(), QTlsPrivate::TlsKeyGeneric::clear(), commonCopyEvent(), QRhiGles2::compileShader(), QUtf8::convertFromUnicode(), QUtf32::convertFromUnicode(), convertParticleData(), QBitArray::count(), QSSGMesh::Mesh::createLightmapUVChannel(), QSslContext::createSsl(), cullLodInstances(), QRingChunk::data(), QPacket::data(), InstanceModel::data(), QMimerSQLResult::data(), QDtlsPrivateOpenSSL::decryptDatagram(), Parser::defaultErrorMsg(), QNetworkReplyWasmImplPrivate::doSendRequest(), QRasterPaintEngine::drawTextItem(), QAbstractItemModel::dropMimeData(), QAbstractTableModel::dropMimeData(), QAbstractListModel::dropMimeData(), QStandardItemModel::dropMimeData(), DragDropListModel::dropMimeData(), QRhiD3D11::enqueueResourceUpdates(), QRhiGles2::enqueueResourceUpdates(), QRhiVulkan::enqueueResourceUpdates(), escapedString(), QODBCResult::exec(), QFontconfigDatabase::fallbacksForFamily(), QIBaseResultPrivate::fetchArray(), QIBaseResultPrivate::fetchBlob(), AndroidCameraPrivate::fetchLastPreviewFrame(), QBitArray::fill(), QXcbClipboardMime::formats_sys(), QMYSQLDriver::formatValue(), QSSGMesh::Mesh::fromAssetData(), QBitArray::fromBits(), QString::fromLatin1(), QSSGMesh::Mesh::fromRuntimeData(), Generator::generateCode(), QQuickDragEvent::getDataAsArrayBuffer(), QTlsPrivate::TlsCryptographOpenSSL::handleNewSessionTicket(), QTlsPrivate::X509CertificateSchannel::importPkcs12(), QRhiGles2::linkProgram(), QSvgIOHandlerPrivate::load(), QSSGLoadedTexture::loadTextureData(), LowEnergyNotificationHub::lowEnergy_characteristicWritten(), macValue(), QMemoryVideoBuffer::map(), notifyNewPreviewFrame(), notifyPictureCaptured(), QWinRTLowEnergyServiceHandler::obtainCharList(), QIBaseDriver::open(), QODBCDriver::open(), QHaikuServices::openUrl(), operator>>(), operator[](), QV4DebugClientPrivate::packMessage(), QPdfDocument::pageLabel(), QTlsPrivate::X509CertificateGeneric::parse(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), QSSGParticleBuffer::pointer(), QODBCResult::prepare(), QPcscSlotName::ptr(), q_fromPercentEncoding(), qMakeOCINumber(), qMakeOCINumber(), QTest::qPrintDataTags(), qStringAsUcs2Le(), qt_string_SQLSetConnectAttr(), QPulseAudioSource::read(), QWindowsAudioSource::read(), QByteDataBuffer::read(), QSSGMesh::MeshInternal::readMeshData(), QOCICols::readPiecewise(), QNonContiguousByteDeviceIoDeviceImpl::readPointer(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QSGBatchRenderer::Allocator< Type, PageSize >::release(), QInternalMimeData::renderDataHelper(), replace(), replace(), QODBCResult::reset(), QBitArray::resize(), QMainWindowLayoutState::restoreState(), QInternalMimeData::retrieveData(), QXcbClipboardMime::retrieveData_sys(), QOpenGLProgramBinaryCache::save(), scanLangEnv(), QNearFieldTargetPrivateImpl::sendCommand(), QQuick3DSkin::setInverseBindPoses(), QWidget::setLayout(), QHaikuClipboard::setMimeData(), QQnxClipboard::setMimeData(), QMacPasteboard::setMimeData(), QRhiD3D11::setPipelineCacheData(), QOpenXRGraphicsVulkan::setupGraphics(), QQuick3DParticleInstanceTable::sort(), sortInstances(), QPacket::squeezedData(), QWasmAudioSink::start(), QWasmAudioSource::start(), QWindowsFontDatabaseBase::EmbeddedFont::tableDirectoryEntry(), QTimeZonePrivate::territory(), QClipboard::text(), toBase64(), trace::toByteArrayFromFlags(), toHex(), QIcc::toIccProfile(), toPercentEncoding(), toStdString(), QTest::toString(), QRhiGles2::trySaveToPipelineCache(), QXcbKeyboard::updateVModMapping(), uuidToByteArray(), winIso639LangName(), wrapInFunction(), RingBuffer::write(), QSocks5SocketEngine::write(), QAsn1Element::write(), QIBaseResultPrivate::writeArray(), QIBaseResultPrivate::writeBlob(), QPNGImageWriter::writeImage(), and QNearFieldTargetPrivateImpl::writeNdefMessages().

+ Here is the call graph for this function:

◆ data() [2/2]

const char * QByteArray::data ( ) const
inlinenoexcept

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 617 of file qbytearray.h.

References d.

◆ data_ptr() [1/2]

DataPtr & QByteArray::data_ptr ( )
inline

Definition at line 504 of file qbytearray.h.

References d.

◆ data_ptr() [2/2]

const DataPointer & QByteArray::data_ptr ( ) const
inline

Definition at line 503 of file qbytearray.h.

References d.

Referenced by QV4::Heap::SharedArrayBuffer::init().

+ Here is the caller graph for this function:

◆ detach()

void QByteArray::detach ( )
inline

Definition at line 625 of file qbytearray.h.

References d, and QArrayData::KeepSize.

Referenced by data(), qtValue(), QWebpHandler::read(), and replace().

+ Here is the caller graph for this function:

◆ end() [1/2]

QByteArray::iterator QByteArray::end ( )
inline

Returns an \l{STL-style iterators}{STL-style iterator} pointing just after the last byte in the byte-array.

iterator-invalidation-func-desc

See also
begin(), constEnd()

Definition at line 447 of file qbytearray.h.

References begin().

Referenced by QBitArray::count(), isLower(), isUpper(), QTimeZonePrivate::isValidId(), and split().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ end() [2/2]

const_iterator QByteArray::end ( ) const
inlinenoexcept

Definition at line 448 of file qbytearray.h.

References begin().

+ Here is the call graph for this function:

◆ endsWith() [1/2]

bool QByteArray::endsWith ( char c) 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 this byte array ends with byte ch; otherwise returns false.

Definition at line 227 of file qbytearray.h.

Referenced by Moc::checkProperties(), QtWaylandClient::convertData(), QFileSystemEngine::createDirectory(), Moc::generate(), QHttpNetworkReplyPrivate::getChunkSize(), Moc::parsePropertyAttributes(), PP_Expression::primary_expression(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), QMimeData::setData(), and TestHTTPServer::wait().

+ Here is the caller graph for this function:

◆ endsWith() [2/2]

bool QByteArray::endsWith ( QByteArrayView bv) const
inline
Since
6.0

Returns true if this byte array ends with the sequence of bytes viewed by bv; otherwise returns false.

Example:

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

Definition at line 228 of file qbytearray.h.

References QtPrivate::endsWith(), and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ erase() [1/2]

Since
6.1

Removes from the byte array the characters in the half-open range [ first , last ). Returns an iterator to the character referred to by last before the erase.

Definition at line 1281 of file qbytearray.cpp.

References begin(), cbegin(), last(), and remove().

Referenced by QtAndroidQuickViewEmbedding::removeRootObjectSignalListener().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ erase() [2/2]

QByteArray::iterator QByteArray::erase ( QByteArray::const_iterator it)
inline

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

Since
6.5

Removes the character denoted by it from the byte array. Returns an iterator to the character immediately after the erased character.

QByteArray ba = "abcdefg";
auto it = ba.erase(ba.cbegin()); // ba is now "bcdefg" and it points to "b"
\inmodule QtCore
Definition qbytearray.h:57
iterator erase(const_iterator first, const_iterator last)
const_iterator cbegin() const noexcept
Definition qbytearray.h:445
QSet< QString >::iterator it
QByteArray ba
[0]

Definition at line 484 of file qbytearray.h.

References erase(), and it.

Referenced by erase().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fill()

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

Sets every byte in the byte array to 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 1943 of file qbytearray.cpp.

References ch, QArrayDataPointer< T >::data(), and resize().

Referenced by QMimeMagicRule::QMimeMagicRule(), leftJustified(), QSGMaterialShaderPrivate::prepare(), rightJustified(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ first() [1/2]

QByteArray QByteArray::first ( qsizetype n) &&
inline

Definition at line 207 of file qbytearray.h.

References resize().

+ Here is the call graph for this function:

◆ first() [2/2]

QByteArray QByteArray::first ( qsizetype n) const &
inline

Definition at line 196 of file qbytearray.h.

Referenced by QMacMimePlainTextFallback::convertToMime(), QMacMimeUnicodeText::convertToMime(), QMacMimeTraditionalMacPlainText::convertToMime(), QGuiApplicationPrivate::createPlatformIntegration(), prepareCustomShader(), QByteDataBuffer::read(), QThreadPoolPrivate::tryToStartMoreThreads(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ fromBase64()

QByteArray QByteArray::fromBase64 ( const QByteArray & base64,
Base64Options options = Base64Encoding )
static
Since
5.2

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

For example:

QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data(); // returns "Qt is great!"
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"

The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.

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

Note
The fromBase64Encoding() function is recommended in new code.
See also
toBase64(), fromBase64Encoding()

Definition at line 4643 of file qbytearray.cpp.

References QByteArray(), and fromBase64Encoding().

Referenced by QtObject::atob(), QAuthenticatorPrivate::calculateResponse(), QTlsPrivate::X509CertificateOpenSSL::certificatesFromPem(), QTlsPrivate::X509CertificateGeneric::certificatesFromPem(), createImageNode(), QSslDiffieHellmanParameters::defaultParameters(), QTlsPrivate::TlsKeyOpenSSL::derFromPem(), QTlsPrivate::TlsKeyGeneric::derFromPem(), qDecodeDataUrl(), dom::DataTransfer::toMimeDataWithFile(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fromBase64Encoding() [1/2]

QByteArray::FromBase64Result QByteArray::fromBase64Encoding ( const QByteArray & base64,
Base64Options options = Base64Encoding )
static
Since
5.15 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

For example:

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

The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.

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

See also
toBase64()

Definition at line 4607 of file qbytearray.cpp.

References Qt::Uninitialized.

◆ fromBase64Encoding() [2/2]

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

Definition at line 4590 of file qbytearray.cpp.

References fromBase64Encoding().

Referenced by fromBase64(), fromBase64Encoding(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ 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 4661 of file qbytearray.cpp.

References ch, QtMiscUtils::fromHex(), i, and Qt::Uninitialized.

Referenced by QMimeMagicRule::QMimeMagicRule(), decodeFrame(), QTlsPrivate::TlsKeyGeneric::decodePem(), MyClass::enableCharNotifications(), QMimerSQLResult::exec(), qt_qmlDebugSendDataToService(), settings_key_to_host_name(), wrapInFunction(), and QLowEnergyControllerPrivateBluezDBus::writeDescriptor().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ fromPercentEncoding()

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

Decodes input from URI/URL-style percent-encoding.

Returns a byte array containing the decoded text. The percent parameter allows use of a different character than '' (for instance, '_' or '=') as the escape character. Equivalent to input.percentDecoded(percent).

For example:

qDebug("%s", text.data()); // reports "Qt is great!"
See also
percentDecoded()

Definition at line 4801 of file qbytearray.cpp.

Referenced by QUrl::fromPercentEncoding(), qDecodeDataUrl(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ fromRawData()

QByteArray QByteArray::fromRawData ( const char * data,
qsizetype size )
inlinestatic

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 \l{implicitly shared} class and the instance returned by this function contains the data pointer, the caller must not delete data or modify it directly as long as the returned QByteArray and any copies exist. However, QByteArray does not take ownership of data, so the QByteArray destructor will never delete the raw data, even when the last QByteArray referring to data is destroyed.

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

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

static const char mydata[] = {
'\x00', '\x00', '\x03', '\x84', '\x78', '\x9c', '\x3b', '\x76',
'\xec', '\x18', '\xc3', '\x31', '\x0a', '\xf1', '\xcc', '\x99',
...
'\x6d', '\x5b'
};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
...
Warning
A byte array created with fromRawData() is not '\0'-terminated, unless the raw data contains a '\0' byte 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 409 of file qbytearray.h.

References QByteArray().

Referenced by QHttpMultiPartPrivate::QHttpMultiPartPrivate(), QMimeMagicRule::QMimeMagicRule(), QT_BEGIN_NAMESPACE::VertexBufferDataExt::addVertexAttributeData(), HeaderName::asByteArray(), QtCbor::ByteData::asByteArrayView(), QSSGRhiShaderPipeline::bindingForTexture(), QTlsPrivate::X509CertificateOpenSSL::certificatesFromPem(), QTlsPrivate::X509CertificateGeneric::certificatesFromPem(), QMimerSQLResult::data(), QPSQLResult::data(), QMetaObjectPrivate::decodeMethodSignature(), QTranslatorPrivate::do_load(), AVFImageCapture::doCapture(), encodeByteArray(), QtWaylandClient::QWaylandExtendedSurface::extended_surface_set_generic_property(), fileArchitecture(), QPlatformPixmap::fromData(), QRasterPlatformPixmap::fromData(), QImage::fromData(), getData(), getQtLibsFromElf(), QSSGBuiltInRhiShaderCache::getRhienvironmentmapPreFilterShader(), QSSGBuiltInRhiShaderCache::getRhiSkyBoxShader(), QLocationUtils::getSatInfoFromNmea(), ICOReader::iconAt(), QSvgTinyDocument::isLikelySvg(), iterateInPluginMetaData(), QOpenGLProgramBinaryCache::load(), QSvgIOHandlerPrivate::load(), QQuick3DFileInstancing::loadFromBinaryFile(), QPSQLResult::numRowsAffected(), parseAttributeValues(), QSSGShaderCustomMaterialAdapter::prepareCustomShader(), dtlsbio::q_dgram_write(), qAppFileName(), qlocationutils_readGga(), qlocationutils_readGll(), qlocationutils_readGsa(), qlocationutils_readGsa(), qlocationutils_readRmc(), qlocationutils_readVtg(), qlocationutils_readZda(), qMetaTypeCustomType_unlocked(), qt_socks5_set_host_address_and_port(), qt_socks5_set_host_name_and_port(), QWebpHandler::read(), readOrMapFile(), readStr(), HciManager::sendConnectionUpdateCommand(), QWaylandKeyboardPrivate::sendEnter(), setRawData(), Http2::settingsFrameToBase64(), QSSGRhiShaderPipeline::setUniform(), QSSGRhiShaderPipeline::setUniformArray(), QTlsBackend::setupClientPskAuth(), stringData(), stringData(), toDouble(), QTlsPrivate::X509CertificateGeneric::toPem(), QTlsPrivate::TlsKeyGeneric::toPem(), QQuickStyledTextPrivate::toRoman(), VDMListDelegateDataType::toUtf8(), QResource::uncompressedData(), QSslSocketPrivate::unixRootCertDirectories(), QVideoTextureHelper::updateTextureWithMap(), wrapInFunction(), QSocks5SocketEngine::write(), QtWaylandClient::QWaylandTextInputv1::zwp_text_input_v1_modifiers_map(), and QtWaylandClient::QWaylandTextInputv2::zwp_text_input_v2_modifiers_map().

+ Here is the call graph for this function:

◆ fromStdString()

QByteArray QByteArray::fromStdString ( const std::string & str)
static
Since
5.4

Returns a copy of the str string as a QByteArray.

See also
toStdString(), QString::fromStdString()

Definition at line 4813 of file qbytearray.cpp.

References QByteArray().

Referenced by dom::DataTransfer::toMimeDataWithFile().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ front() [1/2]

char & QByteArray::front ( )
inline
Since
5.10

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

This function is provided for STL compatibility.

Warning
Calling this function on an empty byte array constitutes undefined behavior.
See also
back(), at(), operator[]()

Definition at line 654 of file qbytearray.h.

References operator[]().

+ Here is the call graph for this function:

◆ front() [2/2]

char QByteArray::front ( ) const
inline
Since
5.10

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

This function is provided for STL compatibility.

Warning
Calling this function on an empty byte array constitutes undefined behavior.
See also
back(), at(), operator[]()

Definition at line 134 of file qbytearray.h.

References at.

Referenced by QAsn1Element::toInfo().

+ Here is the caller graph for this function:

◆ indexOf() [1/2]

qsizetype QByteArray::indexOf ( char ch,
qsizetype 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 start of the first occurrence of the byte ch in this byte array, searching forward from index position from.

Returns -1 if no match is 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()

Referenced by QtAndroidQuickViewEmbedding::addRootObjectSignalListener(), QSSGStageGeneratorBase::buildShaderSourcePass2(), contains(), contains(), QHttpNetworkReplyPrivate::getChunkSize(), QIBusPlatformInputContextPrivate::getSocketPath(), QMetaMethodBuilderPrivate::name(), patchQtCore(), qualifiedNameEquals(), replace(), searchIncludePaths(), split(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ indexOf() [2/2]

qsizetype QByteArray::indexOf ( QByteArrayView bv,
qsizetype from = 0 ) const
inline
Since
6.0

Returns the index position of the start of the first occurrence of the sequence of bytes viewed by bv in this byte array, searching forward from index position from. Returns -1 if no match is found.

Example:

QByteArray x("sticky question");
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 141 of file qbytearray.h.

References QtPrivate::findByteArray(), and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ insert() [1/6]

QByteArray & QByteArray::insert ( qsizetype i,
char ch )
inline

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

array-grow-at-insertion

Definition at line 321 of file qbytearray.h.

References i, and insert().

+ Here is the call graph for this function:

◆ insert() [2/6]

QByteArray & QByteArray::insert ( qsizetype i,
const char * s )
inline

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

array-grow-at-insertion

The function is equivalent to {insert(i, QByteArrayView(s))}

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

Definition at line 316 of file qbytearray.h.

References i, and insert().

+ Here is the call graph for this function:

◆ insert() [3/6]

QByteArray & QByteArray::insert ( qsizetype i,
const char * data,
qsizetype len )
inline

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

Inserts len bytes, starting at data, at position i in the byte array.

array-grow-at-insertion

Definition at line 323 of file qbytearray.h.

References i, and insert().

+ Here is the call graph for this function:

◆ insert() [4/6]

QByteArray & QByteArray::insert ( qsizetype i,
const QByteArray & data )
inline

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

array-grow-at-insertion

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

Definition at line 318 of file qbytearray.h.

References i, and insert().

+ Here is the call graph for this function:

◆ insert() [5/6]

QByteArray & QByteArray::insert ( qsizetype i,
QByteArrayView data )
Inserts \a data at index position \a i and returns a
reference to this byte array.

Example:
\snippet code/src_corelib_text_qbytearray.cpp 17
\since 6.0

For large byte arrays, this operation can be slow (\l{linear time}),
because it requires moving all the bytes at indexes \a i and
above by at least one position further in memory.

! [array-grow-at-insertion] This array grows to accommodate the insertion. If i is beyond the end of the array, the array is first extended with space characters to reach this i. ! [array-grow-at-insertion]

\sa append(), prepend(), replace(), remove()

Definition at line 2238 of file qbytearray.cpp.

References QString::data(), QArrayDataPointer< T >::data(), QArrayDataPointer< T >::detachAndGrow(), i, insert(), Q_CHECK_PTR(), QtPrivate::q_points_into_range(), QArrayDataPointer< T >::size, and str.

Referenced by activeConditions(), QtAndroidQuickViewEmbedding::addRootObjectSignalListener(), QLowEnergyControllerPrivate::addServiceHelper(), append(), insert(), prepend(), replace(), TestHTTPServer::wait(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ insert() [6/6]

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

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

Since
5.7

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

array-grow-at-insertion

Definition at line 2323 of file qbytearray.cpp.

References ch, QArrayDataPointer< T >::data(), QArrayDataPointer< T >::detachAndGrow(), i, Q_CHECK_PTR(), and QArrayDataPointer< T >::size.

+ Here is the call graph for this function:

◆ isDetached()

bool QByteArray::isDetached ( ) const
inline

Definition at line 627 of file qbytearray.h.

References d.

Referenced by assign(), and QRingChunk::isShared().

+ Here is the caller graph for this function:

◆ isEmpty()

bool QByteArray::isEmpty ( ) const
inlinenoexcept

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

Example:

See also
size()

Definition at line 107 of file qbytearray.h.

Referenced by QT_BEGIN_NAMESPACE::DeviceIntegration::DeviceIntegration(), QSGRenderContext::FontKey::FontKey(), QDBusBlockingCallWatcher::QDBusBlockingCallWatcher(), QFontEngineFT::QFontEngineFT(), QGstreamerVideoOverlay::QGstreamerVideoOverlay(), QMimeMagicRule::QMimeMagicRule(), QTextureFileHandler::QTextureFileHandler(), QHttpThreadDelegate::~QHttpThreadDelegate(), QFileSystemEngine::absoluteName(), QWizardPrivate::addField(), addFunction(), QDBusMarshaller::append(), QDBusMarshaller::append(), AVFMediaPlayer::audioOutputChanged(), QProcEnvValue::bytes(), QAuthenticatorPrivate::calculateResponse(), QQmlXMLHttpRequest::charset(), QNetworkRequestFactory::clearBearerToken(), QXcbConnection::clientLeader(), QPdfDocument::close(), codesignBundle(), codesignFile(), commonCopyEvent(), QWindowsMimeImage::convertFromMime(), QXcbWindow::create(), QD3D11Buffer::create(), QD3D11RenderBuffer::create(), QD3D11Texture::create(), QD3D11GraphicsPipeline::create(), QD3D11ComputePipeline::create(), QMetalBuffer::create(), QMetalRenderBuffer::create(), QMetalTexture::create(), QSSGMesh::Mesh::createLightmapUVChannel(), QGuiApplicationPrivate::createPlatformIntegration(), createReadHandlerHelper(), QtWaylandClient::QWaylandDataSource::data_source_send(), QTest::defaultEventDelay(), QTest::defaultKeyDelay(), QTest::defaultMouseDelay(), deployQmlImports(), QAVFCameraBase::device(), QAuthenticatorPrivate::digestMd5Response(), QNetworkReplyWasmImplPrivate::doSendRequest(), QPdfEnginePrivate::drawTextItem(), QRhiD3D11::enqueueSubresUpload(), QRhiGles2::enqueueSubresUpload(), QRhiMetal::enqueueSubresUpload(), QColorSpacePrivate::equals(), QNetworkReplyHttpImplPrivate::fetchCacheMetaData(), QSSGRenderEffect::finalizeShaders(), QFreeTypeFontDatabase::fontEngine(), QImageReader::format(), QString::fromLocal8Bit(), QString::fromUtf8(), Generator::generateCode(), Preamble::get(), QFreetypeFace::getFace(), QXcbScreen::getName(), getRequestedDisplays(), getRhiImplementation(), QNdefNfcSmartPosterRecord::hasIcon(), QColorSpace::iccProfile(), QNdefNfcSmartPosterRecord::icon(), QWaylandCompositorPrivate::init(), QQuickMaterialStyle::initGlobals(), QFontEngine::initializeHeightMetrics(), QGeoFileTileCache::insert(), QFileSystemEntry::isEmpty(), QNdefRecord::isEmpty(), QTimeZonePrivate::isValid(), QTextureFileData::isValid(), QSignalSpy::isValid(), QSSGLightmapUVGeneratorResult::isValid(), QQnxWindow::joinWindowGroup(), QWaylandCompositorPrivate::loadClientBufferIntegration(), QKmsScreenConfig::loadConfig(), QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(), QFontEngine::loadKerningPairs(), main(), make_user_path_without_qstandard_paths(), QOpenGLContext::makeCurrent(), matches(), QQmlXMLHttpRequest::mimeType(), QArgumentType::name(), QNetworkRequestFactoryPrivate::newRequest(), QIBaseDriver::open(), QProcEnvValue::operator==(), QSSGQmlUtilities::outputTextureAsset(), Moc::parseFunction(), Moc::parseInterfaces(), Moc::parseMaybeFunction(), Moc::parsePluginData(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), percentDecoded(), QHttpNetworkConnectionChannel::pipelineFlush(), QRhiVulkan::prepareUploadSubres(), Scanner::process(), processSentence(), QIOPipePrivate::pushData(), q_fromPercentEncoding(), QPulseAudioSource::read(), QWindowsAudioSource::read(), QJpegHandlerPrivate::read(), read32bitIcon(), QIOPipePrivate::readAvailableData(), QSystemLocaleData::readEnvironment(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), QSGCompressedAtlasTexture::Texture::removedFromAtlas(), QWizardPrivate::removeFieldAt(), QInternalMimeData::renderDataHelper(), repeated(), QNetworkReplyHttpImplPrivate::replyDownloadMetaData(), QPlatformInputContextFactory::requested(), requiredQtContainers(), QWizardField::resolve(), QSSGLightmapUVGenerator::run(), runMoc(), HciManager::sendCommand(), QHttpProtocolHandler::sendRequest(), set_text(), QWasmCamera::setCamera(), QNetworkHeadersPrivate::setCookedHeader(), QTimeLinePrivate::setCurrentTime(), QNdefNfcSmartPosterRecord::setPayload(), shouldIncludeFs(), QStandardPaths::standardLocations(), QProcEnvValue::string(), QQmlLSQuickCompletionPlugin::suggestSnippetsForLeftHandSideOfBinding(), QQmlLSQuickCompletionPlugin::suggestSnippetsForRightHandSideOfBinding(), toHex(), QAsn1Element::toInteger(), FunctionDef::toJson(), PropertyDef::toJson(), EnumDef::toJson(), QQmlPropertyCache::toMetaObjectBuilder(), QAsn1Element::toObjectId(), toPercentEncoding(), QNetworkCookie::toRawForm(), AVFCameraSession::updateAudioOutput(), QXcbIntegration::wmClass(), QImageWriter::write(), QTiffHandler::write(), QTextDocumentWriter::write(), write_icc_profile(), QPdfEnginePrivate::writeHeader(), QPNGImageWriter::writeImage(), QSSGQmlUtilities::writeQmlForAnimation(), and QtWaylandClient::QWaylandPrimarySelectionSourceV1::zwp_primary_selection_source_v1_send().

◆ isLower()

bool QByteArray::isLower ( ) const

Returns true if this byte array is lowercase, that is, if it's identical to its toLower() folding.

Note that this does not mean that the byte array only contains lowercase letters; only that it contains no ASCII uppercase letters.

Since
5.12
See also
isUpper(), toLower()

Definition at line 3036 of file qbytearray.cpp.

References begin(), end(), and isUpperCaseAscii().

+ Here is the call graph for this function:

◆ isNull()

bool QByteArray::isNull ( ) const
noexcept

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

Referenced by QMetaMethodBuilderPrivate::QMetaMethodBuilderPrivate(), QPpdPrintDevice::QPpdPrintDevice(), append(), QQmlLoggingCategory::componentComplete(), QString::fromLocal8Bit(), QString::fromUtf8(), QSslDiffieHellmanParameters::isEmpty(), QSslConfiguration::isNull(), operator<<(), QFile::rename(), replace(), QMimeDataPrivate::retrieveTypedData(), QQnxWindow::setVisible(), and toPercentEncoding().

+ Here is the caller graph for this function:

◆ isSharedWith()

bool QByteArray::isSharedWith ( const QByteArray & other) const
inlinenoexcept

Definition at line 127 of file qbytearray.h.

References other().

+ Here is the call graph for this function:

◆ isUpper()

bool QByteArray::isUpper ( ) const

Returns true if this byte array is uppercase, that is, if it's identical to its toUpper() folding.

Note that this does not mean that the byte array only contains uppercase letters; only that it contains no ASCII lowercase letters.

Since
5.12
See also
isLower(), toUpper()

Definition at line 3020 of file qbytearray.cpp.

References begin(), end(), and isLowerCaseAscii().

+ Here is the call graph for this function:

◆ isValidUtf8()

QByteArray::isValidUtf8 ( ) const
inlinenoexcept

Returns true if this byte array contains valid UTF-8 encoded data, or false otherwise.

Since
6.3

Definition at line 234 of file qbytearray.h.

References QtPrivate::isValidUtf8(), and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ last() [1/2]

QByteArray QByteArray::last ( qsizetype n) &&
inline

Definition at line 213 of file qbytearray.h.

◆ last() [2/2]

QByteArray QByteArray::last ( qsizetype n) const &
inline

Definition at line 198 of file qbytearray.h.

Referenced by erase(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ lastIndexOf() [1/3]

qsizetype QByteArray::lastIndexOf ( char ch,
qsizetype 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 start of the last occurrence of byte ch in this byte array, searching backward from index position from.

If from is -1 (the default), the search starts at the last byte (at index size() - 1). Returns -1 if no match is 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()

Referenced by Generator::generateCode(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ lastIndexOf() [2/3]

qsizetype QByteArray::lastIndexOf ( QByteArrayView bv) const
inline
Since
6.2 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 start of the last occurrence of the sequence of bytes viewed by bv in this byte array, searching backward from the end of the byte array. Returns -1 if no match is found.

Example:

QByteArray x("crazy azimuths");
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 146 of file qbytearray.h.

References lastIndexOf().

+ Here is the call graph for this function:

◆ lastIndexOf() [3/3]

qsizetype QByteArray::lastIndexOf ( QByteArrayView bv,
qsizetype from ) const
inline
Since
6.0

Returns the index position of the start of the last occurrence of the sequence of bytes viewed by bv in this byte array, searching backward from index position from.

negative-index-start-search-from-end

Returns -1 if no match is found.

Example:

QByteArray x("crazy azimuths");
x.lastIndexOf(y); // returns 6
x.lastIndexOf(y, 6); // returns 6
x.lastIndexOf(y, 5); // returns 2
x.lastIndexOf(y, 1); // returns -1
Note
When searching for a 0-length bv, the match at the end of the data is excluded from the search by a negative from, even though {-1} is normally thought of as searching from the end of the byte array: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value for from or omit the from parameter entirely.
See also
indexOf(), contains(), count()

Definition at line 148 of file qbytearray.h.

References QtPrivate::lastIndexOf(), and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ left() [1/2]

QByteArray QByteArray::left ( qsizetype n) &&
inline

Definition at line 175 of file qbytearray.h.

References qMax().

+ Here is the call graph for this function:

◆ left() [2/2]

QByteArray QByteArray::left ( qsizetype n) const &
inline

Definition at line 169 of file qbytearray.h.

References qMax().

Referenced by QResponseApdu::QResponseApdu(), Moc::checkProperties(), createDirectoryWithParents(), QSSGShaderKeyUnsigned< TBitWidth >::fromString(), Generator::generateCode(), QIBusPlatformInputContextPrivate::getSocketPath(), QMetaMethodBuilderPrivate::name(), noRef(), QTlsPrivate::X509CertificateGeneric::parse(), read_xpm_body(), and searchIncludePaths().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ leftJustified()

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

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

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 3683 of file qbytearray.cpp.

References fill(), and truncate().

Referenced by wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ length()

qsizetype QByteArray::length ( ) const
inlinenoexcept

◆ max_size()

qsizetype QByteArray::max_size ( )
inlinestaticconstexprnoexcept
Since
6.8

This function is provided for STL compatibility. It returns the maximum number of elements that the byte array can theoretically hold. In practice, the number can be much smaller, limited by the amount of memory available to the system.

Definition at line 485 of file qbytearray.h.

Referenced by QSctpSocketPrivate::canReadNotification(), QRingBuffer::chop(), QRingBuffer::free(), QIODevice::readAll(), QIODevice::readLine(), QCborStreamReaderPrivate::readStringChunk_byte(), QRingBuffer::reserve(), and QRingBuffer::reserveFront().

+ Here is the caller graph for this function:

◆ mid() [1/2]

QByteArray QByteArray::mid ( qsizetype index,
qsizetype len = -1 ) &&

Definition at line 3122 of file qbytearray.cpp.

References pos, QByteArray(), and resize().

+ Here is the call graph for this function:

◆ mid() [2/2]

◆ number() [1/7]

QByteArray QByteArray::number ( double n,
char format = 'g',
int precision = 6 )
static

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 representing the floating-point number n as text.

Returns a byte array containing a string representing n, with a given format and precision, with the same meanings as for \l {QString::number(double, char, int)}. For example:

QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
See also
toDouble(), QLocale::FloatingPointPrecisionOption

Definition at line 4405 of file qbytearray.cpp.

References QLocaleData::DFDecimal, QLocaleData::DFExponent, QLocaleData::DFSignificantDigits, form, isUpperCaseAscii(), qdtoAscii(), qWarning, and QtMiscUtils::toAsciiLower().

+ Here is the call graph for this function:

◆ number() [2/7]

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

Returns a byte-array representing the whole number n as text.

Returns a byte array containing a string representing n, using the specified base (ten by default). Bases 2 through 36 are supported, using letters for digits beyond 9: A is ten, B is eleven and so on.

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 regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
See also
setNum(), toInt()

Definition at line 4326 of file qbytearray.cpp.

References base, and setNum().

Referenced by QAuthenticatorPrivate::QAuthenticatorPrivate(), QXcbVirtualDesktop::QXcbVirtualDesktop(), QXcbXSettings::QXcbXSettings(), Python::WriteImports::acceptUI(), activeConditions(), QGstreamerVideoDevices::addDevice(), QQmlAdaptorModelEngineData::addProperty(), QSSGRenderReflectionMap::addReflectionMapEntry(), QSSGStageGeneratorBase::addShaderPass2Marker(), QSSGStageGeneratorBase::addShaderUniformMap(), alignedNumber(), buildDevicePath(), QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(), checkXdgRuntimeDir(), QWindowsMimeHtml::convertFromMime(), QMetalBuffer::create(), QXcbSystemTrayTracker::create(), createCameraDevice(), QQmlPropertyCacheCreatorBase::createClassNameForInlineComponent(), QQmlPropertyCacheCreatorBase::createClassNameTypeByUrl(), QQmlPropertyCacheCreator< ObjectContainer >::createMetaObject(), QQmlOpenMetaObjectType::createProperties(), QQmlDMObjectDataMetaObject::createProperty(), QQmlOpenMetaObjectType::createProperty(), debugShowWindowCmd(), debugWindowPlacementFlags(), debugWinExStyle(), debugWinStyle(), debugWinSwpPos(), QAuthenticatorPrivate::digestMd5Response(), fileIdWin8(), QSSGRenderEffect::finalizeShaders(), QTest::formatResult(), QRhiGles2::gatherUniforms(), generateFragmentShader(), AndroidCamera::getCameraInfo(), glFormatName(), QHttpNetworkRequestPrivate::header(), QFileSystemEngine::id(), QSettingsPrivate::iniEscapedString(), QXcbKeyboard::keymapFromCore(), QLockFilePrivate::lockFileContents(), nameForCompressedIcon(), nameForConnector(), QTlsPrivate::X509CertificateGeneric::parse(), Moc::parseClassInfo(), QNetworkReplyHttpImplPrivate::postRequest(), prefixMessage(), QHttpNetworkConnectionPrivate::prepareRequest(), QFontEngine::properties(), QTest::qSignalDumperCallback(), QTest::qSignalDumperCallbackSlot(), rawBytes(), QSSGProgramGenerator::registerShaderMetaDataFromSource(), QV4DebugServiceImpl::sendSomethingToSomebody(), QHttpNetworkHeaderPrivate::setContentLength(), QTimeLinePrivate::setCurrentTime(), setNum(), QRhiVulkan::setObjectName(), QHttpSocketEngine::slotSocketConnected(), QAsn1Element::toObjectId(), toSecondsFormat(), QTest::toString(), QTest::toString(), QTest::toString(), QTest::toString(), QTest::toString(), QTest::toString(), QTest::Internal::toString(), QTest::Internal::toString(), QRhiGles2::tryLoadFromDiskOrPipelineCache(), QNetworkDiskCachePrivate::uniqueFileName(), unixPermissionsText(), QFFmpegMetaData::value(), valueToJson(), TestHTTPServer::wait(), wrapInFunction(), write_pbm_image(), RCCFileInfo::writeDataInfo(), QQmlJSStreamWriter::writeEnumObjectLiteralBinding(), QQmlJSStreamWriter::writeLibraryImport(), and QQmlJSStreamWriter::writeNumberBinding().

+ Here is the call graph for this function:

◆ number() [3/7]

QByteArray QByteArray::number ( long 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
toLong()

Definition at line 4350 of file qbytearray.cpp.

References base, and setNum().

+ Here is the call graph for this function:

◆ number() [4/7]

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 4374 of file qbytearray.cpp.

References base, and setNum().

+ Here is the call graph for this function:

◆ number() [5/7]

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 4386 of file qbytearray.cpp.

References base, and setNum().

+ Here is the call graph for this function:

◆ number() [6/7]

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 4338 of file qbytearray.cpp.

References base, and setNum().

+ Here is the call graph for this function:

◆ number() [7/7]

QByteArray QByteArray::number ( ulong 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
toULong()

Definition at line 4362 of file qbytearray.cpp.

References base, and setNum().

+ Here is the call graph for this function:

◆ operator const char *()

QByteArray::operator const char * ( ) const
inline

Definition at line 606 of file qbytearray.h.

◆ operator const void *()

QByteArray::operator const void * ( ) const
inline
Note
Use constData() instead in new code.

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.

! [pointer-invalidation-desc] The pointer remains valid as long as no detach happens and the QByteArray is not modified. ! [pointer-invalidation-desc]

This operator is mostly useful to pass a byte array to a function
that accepts a \c{const char *}.

You can disable this operator by defining \c
QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.

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

\sa constData()

Definition at line 608 of file qbytearray.h.

◆ operator+=() [1/4]

QByteArray & QByteArray::operator+= ( 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.Appends the byte ch onto the end of this byte array and returns a reference to this byte array.

Definition at line 349 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ 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 '\0'-terminated string str onto the end of this byte array and returns a reference to this byte array.

Definition at line 351 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ 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 \l{implicitly shared} class. Consequently, if you append to an empty byte array, then the byte array will just share the data held in ba. In this case, no copying of data is done, taking \l{constant time}. If a shared instance is modified, it will be copied (copy-on-write), taking \l{linear time}.

If the byte array being appended to is not empty, a deep copy of the data is performed, taking \l{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 353 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ operator+=() [4/4]

QByteArray & QByteArray::operator+= ( QByteArrayView a)
inline

Definition at line 355 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ operator=() [1/2]

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

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

str is assumed to point to a null-terminated string, and its length is determined dynamically.

Definition at line 1357 of file qbytearray.cpp.

References assign(), QArrayDataPointer< T >::clear(), QArrayDataPointer< T >::fromRawData(), and str.

+ Here is the call graph for this function:

◆ operator=() [2/2]

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

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

Definition at line 1341 of file qbytearray.cpp.

References d, and other().

Referenced by append().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ operator[]() [1/2]

char & QByteArray::operator[] ( qsizetype i)
inline

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

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

Example:

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

Definition at line 652 of file qbytearray.h.

References data(), and i.

+ Here is the call graph for this function:

◆ operator[]() [2/2]

char QByteArray::operator[] ( qsizetype 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.Same as at(i).

Definition at line 602 of file qbytearray.h.

References d, and i.

Referenced by back(), and front().

+ Here is the caller graph for this function:

◆ percentDecoded()

QByteArray QByteArray::percentDecoded ( char percent = '%') const
Since
6.4

Decodes URI/URL-style percent-encoding.

Returns a byte array containing the decoded text. The percent parameter allows use of a different character than '' (for instance, '_' or '=') as the escape character.

For example:

QByteArray encoded("Qt%20is%20great%33");
QByteArray decoded = encoded.percentDecoded(); // Set to "Qt is great!"
Note
Given invalid input (such as a string containing the sequence "%G5", which is not a valid hexadecimal number) the output will be invalid as well. As an example: the sequence "%G5" could be decoded to 'W'.
See also
toPercentEncoding(), QUrl::fromPercentEncoding()

Definition at line 4777 of file qbytearray.cpp.

References isEmpty(), and q_fromPercentEncoding().

Referenced by wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ prepend() [1/6]

QByteArray & QByteArray::prepend ( 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.Prepends the byte ch to this byte array.

Definition at line 280 of file qbytearray.h.

References insert().

Referenced by checkLightxml(), QGuiApplicationPrivate::createPlatformIntegration(), Moc::generate(), QSettingsPrivate::iniEscapedKey(), Preprocessor::macroExpandIdentifier(), QTlsPrivate::TlsKeyBase::pemFromDer(), prepend(), Moc::prependNamespaces(), QDBusAbstractAdaptor::setAutoRelaySignals(), QSSGQmlUtilities::valueToQml(), and QAsn1Element::write().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ prepend() [2/6]

QByteArray & QByteArray::prepend ( 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.Prepends the '\0'-terminated string str to this byte array.

Definition at line 283 of file qbytearray.h.

References insert(), and qstrlen().

+ Here is the call graph for this function:

◆ prepend() [3/6]

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

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

Prepends len bytes starting at str to this byte array. The bytes prepended may include '\0' bytes.

Definition at line 285 of file qbytearray.h.

References insert().

+ Here is the call graph for this function:

◆ prepend() [4/6]

QByteArray & QByteArray::prepend ( const QByteArray & a)

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

Definition at line 2019 of file qbytearray.cpp.

References ba, QArrayDataPointer< T >::constAllocatedCapacity(), QArrayDataPointer< T >::isMutable(), prepend(), and size().

+ Here is the call graph for this function:

◆ prepend() [5/6]

QByteArray & QByteArray::prepend ( QByteArrayView ba)
inline

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

This operation is typically very fast (\l{constant time}), because QByteArray preallocates extra space at the beginning of the data, so it can grow without reallocating the entire array each time.

Example:

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

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

See also
append(), insert()

Definition at line 288 of file qbytearray.h.

References insert().

+ Here is the call graph for this function:

◆ prepend() [6/6]

QByteArray & QByteArray::prepend ( qsizetype count,
char ch )
inline

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

Since
5.7

Prepends count copies of byte ch to this byte array.

Definition at line 658 of file qbytearray.h.

References ch, and insert().

+ Here is the call graph for this function:

◆ push_back() [1/4]

void QByteArray::push_back ( 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(ch).

Definition at line 466 of file qbytearray.h.

References append().

Referenced by Scanner::process(), and QQuick3DEffect::updateSpatialNode().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ push_back() [2/4]

void QByteArray::push_back ( 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.Same as append(str).

Definition at line 468 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ push_back() [3/4]

void QByteArray::push_back ( const QByteArray & other)
inline

This function is provided for STL compatibility.

It is equivalent to append(other).

Definition at line 470 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ push_back() [4/4]

void QByteArray::push_back ( QByteArrayView str)
inline
Since
6.0 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 472 of file qbytearray.h.

References append().

+ Here is the call graph for this function:

◆ push_front() [1/4]

void QByteArray::push_front ( 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(ch).

Definition at line 474 of file qbytearray.h.

References prepend().

+ Here is the call graph for this function:

◆ push_front() [2/4]

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 476 of file qbytearray.h.

References prepend().

+ Here is the call graph for this function:

◆ push_front() [3/4]

void QByteArray::push_front ( const QByteArray & other)
inline

This function is provided for STL compatibility.

It is equivalent to prepend(other).

Definition at line 478 of file qbytearray.h.

References prepend().

+ Here is the call graph for this function:

◆ push_front() [4/4]

void QByteArray::push_front ( QByteArrayView str)
inline
Since
6.0 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 480 of file qbytearray.h.

References prepend().

+ Here is the call graph for this function:

◆ rbegin() [1/2]

QByteArray::reverse_iterator QByteArray::rbegin ( )
inline
Since
5.6

Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first byte in the byte-array, in reverse order.

iterator-invalidation-func-desc

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

Definition at line 451 of file qbytearray.h.

◆ rbegin() [2/2]

QByteArray::const_reverse_iterator QByteArray::rbegin ( ) const
inlinenoexcept
Since
5.6 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 453 of file qbytearray.h.

◆ remove()

QByteArray & QByteArray::remove ( qsizetype pos,
qsizetype 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"

Element removal will preserve the array's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the array's size.

See also
insert(), replace(), squeeze()

Definition at line 2361 of file qbytearray.cpp.

References begin(), QArrayDataPointer< T >::begin(), copy(), QArrayDataPointer< T >::data(), QArrayDataPointer< T >::end(), pos, QArrayDataPointer< T >::size, swap(), and Qt::Uninitialized.

Referenced by erase(), QFreetypeFace::getFace(), Moc::parseMocInclude(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), QPulseAudioSource::read(), replace(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ removeAt()

QByteArray & QByteArray::removeAt ( qsizetype pos)
inline
Since
6.5

Removes the character at index pos. If pos is out of bounds (i.e. pos >= size()) this function does nothing.

See also
remove()

Definition at line 327 of file qbytearray.h.

References pos, and remove().

+ Here is the call graph for this function:

◆ removeFirst()

QByteArray & QByteArray::removeFirst ( )
inline
Since
6.5

Removes the first character in this byte array. If the byte array is empty, this function does nothing.

See also
remove()

Definition at line 329 of file qbytearray.h.

References remove().

+ Here is the call graph for this function:

◆ removeIf()

template<typename Predicate >
template< typename Predicate > QByteArray & QByteArray::removeIf ( Predicate pred)
inline
Since
6.1

Removes all bytes for which the predicate pred returns true from the byte array. Returns a reference to the byte array.

See also
remove()

Definition at line 333 of file qbytearray.h.

◆ removeLast()

QByteArray & QByteArray::removeLast ( )
inline
Since
6.5

Removes the last character in this byte array. If the byte array is empty, this function does nothing.

See also
remove()

Definition at line 330 of file qbytearray.h.

References remove().

+ Here is the call graph for this function:

◆ rend() [1/2]

QByteArray::reverse_iterator QByteArray::rend ( )
inline
Since
5.6

Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing just after the last byte in the byte-array, in reverse order.

iterator-invalidation-func-desc

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

Definition at line 452 of file qbytearray.h.

References begin().

+ Here is the call graph for this function:

◆ rend() [2/2]

QByteArray::const_reverse_iterator QByteArray::rend ( ) const
inlinenoexcept
Since
5.6 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 454 of file qbytearray.h.

References begin().

+ Here is the call graph for this function:

◆ repeated()

QByteArray QByteArray::repeated ( qsizetype times) const
Since
4.5

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

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

Example:

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

Definition at line 2648 of file qbytearray.cpp.

References QByteArray(), isEmpty(), and reserve().

Referenced by wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ replace() [1/6]

QByteArray & QByteArray::replace ( char before,
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 before with the byte after.

Definition at line 2606 of file qbytearray.cpp.

References data(), indexOf(), and pos.

+ Here is the call graph for this function:

◆ replace() [2/6]

QByteArray & QByteArray::replace ( char before,
QByteArrayView 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 before with the byte array after.

Definition at line 342 of file qbytearray.h.

◆ replace() [3/6]

QByteArray & QByteArray::replace ( const char * before,
qsizetype bsize,
const char * after,
qsizetype asize )
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 bsize bytes starting at before with the asize bytes starting at after.

Since the sizes of the strings are given by bsize and asize, they may contain '\0' bytes and do not need to be '\0'-terminated.

Definition at line 344 of file qbytearray.h.

◆ replace() [4/6]

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

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

Since
6.0

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

Example:

QByteArray ba("colour behaviour flavour neighbour");
// ba == "color behavior flavor neighbor"

Definition at line 2485 of file qbytearray.cpp.

References copy(), d, data(), QByteArrayView::data(), isNull(), matcher, pos, QtPrivate::q_points_into_range(), replace(), resize(), and QByteArrayView::size().

+ Here is the call graph for this function:

◆ replace() [5/6]

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

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 starting at position after.

The bytes inserted may include '\0' bytes.

Since
4.7

Definition at line 339 of file qbytearray.h.

Referenced by QtAndroidQuickViewEmbedding::addRootObjectSignalListener(), QSSGStageGeneratorBase::buildShaderSourcePass2(), QWindowsMimeHtml::convertToMime(), QFontEngine::convertToPostscriptFontFamilyName(), encodeEntity(), generateQualifiedClassNameIdentifier(), Preamble::get(), Preprocessor::macroExpandIdentifier(), parseAttributeValues(), patchQtCore(), replace(), replace(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ replace() [6/6]

QByteArray & QByteArray::replace ( qsizetype pos,
qsizetype len,
QByteArrayView 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 2434 of file qbytearray.cpp.

References copy(), QArrayDataPointer< T >::data(), detach(), insert(), pos, QtPrivate::q_points_into_range(), remove(), and replace().

+ Here is the call graph for this function:

◆ reserve()

void QByteArray::reserve ( qsizetype 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 in doubt about how much space shall be needed, it is usually better to use an upper bound as size, or a high estimate of the most likely size, if a strict upper bound would be much bigger than this. If size is an underestimate, the array will grow as needed once the reserved size is exceeded, which may lead to a larger allocation than your best overestimate would have and will slow the operation that triggers it.

Warning
reserve() reserves memory but does not change the size of the byte array. Accessing data beyond the end of the byte array is undefined behavior. If you need to access memory beyond the current end of the array, use resize().

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

Definition at line 634 of file qbytearray.h.

References capacity(), d, QArrayData::KeepSize, and qMax().

Referenced by RCCResourceLibrary::RCCResourceLibrary(), QJsonPrivate::Writer::arrayToJson(), QOCIResultPrivate::bindValue(), QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(), QPacket::clear(), QSSGMesh::Mesh::createLightmapUVChannel(), QMimerSQLResult::data(), enquoteByteArray(), QCborContainerPrivate::extractAt_complex(), QODBCDriver::formatValue(), QSqlDriver::formatValue(), QHttpNetworkRequestPrivate::header(), QJsonPrivate::Writer::objectToJson(), QIBaseDriver::open(), QQmlError::operator<<(), QRegularExpression::operator<<(), QSslSocketPrivate::peek(), QSSGShaderCustomMaterialAdapter::prepareCustomShader(), QtPrivate::QByteArrayList_join(), QHttpNetworkReplyPrivate::readHeader(), QHttpNetworkReplyPrivate::readStatus(), repeated(), QDBusPendingCallPrivate::setMetaTypes(), QSocks5SocketEngine::writeDatagram(), and QQmlJSStreamWriter::writeScriptBinding().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ resize() [1/2]

void QByteArray::resize ( qsizetype 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 beyond position size are excluded from the byte array.

Note
While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use squeeze().
See also
size(), truncate(), squeeze()

Definition at line 1880 of file qbytearray.cpp.

References capacity(), QArrayDataPointer< T >::data(), QArrayDataPointer< T >::freeSpaceAtBegin(), QArrayData::Grow, and QArrayDataPointer< T >::size.

Referenced by QQnxIntegration::QQnxIntegration(), QQnxWindow::QQnxWindow(), QVideoFrame::QVideoFrame(), _q_PKCS12_keygen(), _q_PKCS12_salt(), QPdfEnginePrivate::addImage(), QSslContext::cacheSession(), QSctpSocketPrivate::canReadNotification(), chop(), QRhiGles2::compileShader(), convertParticleData(), qstdweb::Uint8Array::copyToQByteArray(), QSSGMesh::Mesh::createLightmapUVChannel(), QMimerSQLResult::data(), QDtlsPrivateOpenSSL::decryptDatagram(), QRhiD3D11::enqueueResourceUpdates(), QRhiGles2::enqueueResourceUpdates(), QRhiVulkan::enqueueResourceUpdates(), escapedString(), QDB2Result::exec(), QODBCResult::exec(), QRhiGles2::executeCommandBuffer(), QIBaseResultPrivate::fetchArray(), QIBaseResultPrivate::fetchBlob(), fill(), QSSGMesh::Mesh::fromAssetData(), QBitArray::fromBits(), QSSGMesh::Mesh::fromRuntimeData(), ProceduralSkyTextureData::generateRGBA16FTexture(), getGlyphData(), QFontEngine::getSfntTable(), QRhiGles2::linkProgram(), QOpenGLDebugLogger::loggedMessages(), LowEnergyNotificationHub::lowEnergy_characteristicWritten(), mergeStringLiterals(), operator>>(), QTlsPrivate::X509CertificateGeneric::parse(), QOpenGLDebugLogger::pushGroup(), QTest::qPrintDataTags(), QPulseAudioSource::read(), QByteDataBuffer::read(), QHttpNetworkReplyPrivate::readBodyFast(), QSSGMesh::MeshInternal::readMeshData(), QOCICols::readPiecewise(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QInternalMimeData::renderDataHelper(), replace(), QSSGParticleBuffer::resize(), RingBuffer::resize(), QBitArray::resize(), resize(), resizeForOverwrite(), QRhiNull::resourceUpdate(), QMainWindowLayoutState::restoreState(), QSGAreaAllocator::serialize(), setMonitorDataFromSetupApi(), QQmlPreviewFileEngine::setSize(), QOpenXRGraphicsVulkan::setupGraphics(), QQuick3DParticleInstanceTable::sort(), QRingChunk::toByteArray(), QSSGShaderDefaultMaterialKey::toByteArray(), QTlsPrivate::TlsCryptographSchannel::transmit(), truncate(), QQuick3DSkin::updateSpatialNode(), uuidToByteArray(), QSSGShaderDefaultMaterialKey::StringVisitor::visit(), wrapInFunction(), and QIBaseResultPrivate::writeArray().

+ Here is the call graph for this function:

◆ resize() [2/2]

void QByteArray::resize ( qsizetype newSize,
char c )
Since
6.4

Sets the size of the byte array to newSize bytes.

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

If newSize is less than the current size, bytes beyond position newSize are excluded from the byte array.

Note
While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use squeeze().
See also
size(), truncate(), squeeze()

Definition at line 1910 of file qbytearray.cpp.

References QArrayDataPointer< T >::data(), resize(), and QArrayDataPointer< T >::size.

+ Here is the call graph for this function:

◆ resizeForOverwrite()

void QByteArray::resizeForOverwrite ( qsizetype size)
Since
6.8

Resizes the byte array to size bytes. If the size of the byte array grows, the new bytes are uninitialized.

The behavior is identical to {resize(size)}.

See also
resize()

Definition at line 1928 of file qbytearray.cpp.

References resize().

+ Here is the call graph for this function:

◆ right() [1/2]

QByteArray QByteArray::right ( qsizetype n) &&
inline

Definition at line 187 of file qbytearray.h.

References qMax().

+ Here is the call graph for this function:

◆ right() [2/2]

QByteArray QByteArray::right ( qsizetype n) const &
inline

Definition at line 181 of file qbytearray.h.

References qMax().

Referenced by clientChallenge(), QSSGShaderKeyUnsigned< TBitWidth >::fromString(), and QTlsPrivate::Q_GLOBAL_STATIC_WITH_ARGS().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ rightJustified()

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

Returns a byte array of size width that contains the fill byte 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 3720 of file qbytearray.cpp.

References fill(), and truncate().

Referenced by wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setNum() [1/10]

QByteArray & QByteArray::setNum ( double n,
char format = 'g',
int precision = 6 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Represent the floating-point number n as text.

Sets this byte array to a string representing n, with a given format and precision (with the same meanings as for \l {QString::number(double, char, int)}), and returns a reference to this byte array.

See also
toDouble(), QLocale::FloatingPointPrecisionOption

Definition at line 4292 of file qbytearray.cpp.

References number().

+ Here is the call graph for this function:

◆ setNum() [2/10]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Represent the floating-point number n as text.

Sets this byte array to a string representing n, with a given format and precision (with the same meanings as for \l {QString::number(double, char, int)}), and returns a reference to this byte array.

See also
toFloat()

Definition at line 700 of file qbytearray.h.

References setNum().

+ Here is the call graph for this function:

◆ setNum() [3/10]

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

Represent the whole number n as text.

Sets this byte array to a string representing n in base base (ten by default) and returns a reference to this byte array. Bases 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
See also
number(), toInt()

Definition at line 692 of file qbytearray.h.

References base, and setNum().

+ Here is the call graph for this function:

◆ setNum() [4/10]

QByteArray & QByteArray::setNum ( long 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
toLong()

Definition at line 696 of file qbytearray.h.

References base, and setNum().

+ Here is the call graph for this function:

◆ setNum() [5/10]

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 4244 of file qbytearray.cpp.

References append(), base, clear(), and qulltoa2().

+ Here is the call graph for this function:

◆ setNum() [6/10]

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 4269 of file qbytearray.cpp.

References append(), base, clear(), and qulltoa2().

+ Here is the call graph for this function:

◆ setNum() [7/10]

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 688 of file qbytearray.h.

References base, and setNum().

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

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setNum() [8/10]

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 694 of file qbytearray.h.

References base, and setNum().

+ Here is the call graph for this function:

◆ setNum() [9/10]

QByteArray & QByteArray::setNum ( ulong 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
toULong()

Definition at line 698 of file qbytearray.h.

References base, and setNum().

+ Here is the call graph for this function:

◆ setNum() [10/10]

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 690 of file qbytearray.h.

References base, and setNum().

+ Here is the call graph for this function:

◆ setRawData()

QByteArray & QByteArray::setRawData ( const char * data,
qsizetype size )
Since
4.7

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

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

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

Definition at line 4479 of file qbytearray.cpp.

References clear(), and fromRawData().

+ Here is the call graph for this function:

◆ shrink_to_fit()

void QByteArray::shrink_to_fit ( )
inline
Since
5.10

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

Definition at line 482 of file qbytearray.h.

◆ simplified() [1/2]

QByteArray QByteArray::simplified ( ) &&
inline

Definition at line 268 of file qbytearray.h.

◆ simplified() [2/2]

QByteArray QByteArray::simplified ( ) const &
inline

Definition at line 266 of file qbytearray.h.

Referenced by pullFiles(), read_xpm_body(), setMatrix(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ size()

qsizetype QByteArray::size ( ) const
inlinenoexcept

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 \l{fromRawData()}{raw data} that didn't include the trailing '\0'-termination byte, then QByteArray doesn't add it automatically unless a \l{deep copy} is created.

Example:

QByteArray ba("Hello");
qsizetype 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 494 of file qbytearray.h.

References d.

Referenced by QBitArray::QBitArray(), QCborValue::QCborValue(), QHttpMultiPartPrivate::QHttpMultiPartPrivate(), QMimeMagicRule::QMimeMagicRule(), QNetworkReplyDataImpl::QNetworkReplyDataImpl(), QOscMessage::QOscMessage(), QQnxIntegration::QQnxIntegration(), QQnxWindow::QQnxWindow(), QResponseApdu::QResponseApdu(), QTemporaryFileName::QTemporaryFileName(), _q_lower(), _q_upper(), QFileSystemEngine::absoluteName(), QQuick3DParticleInstanceTable::addInstance(), QGeoFileTileCache::addToDiskCache(), QGeoFileTileCache::addToMemoryCache(), QRingChunk::allocate(), append(), QCborStreamWriter::append(), QConcatenable< QByteArray >::appendTo(), QtStringBuilder::appendToByteArray(), appendVariant(), QJsonPrivate::Writer::arrayToJson(), QPdf::ascii85Encode(), QRingChunk::assign(), assign(), QRingChunk::available(), RingBuffer::availableDataBlockSize(), QSocks5PasswordAuthenticator::beginAuthenticate(), QOCIResultPrivate::bindValue(), QSSGParticleBuffer::bufferSize(), QCommandApdu::build(), QSSGMeshBVHBuilder::buildTree(), QAudioBuffer::byteCount(), QHttpPartPrivate::bytesAvailable(), QHttpNetworkReplyPrivate::bytesAvailable(), RingBuffer::bytesOfDataInBuffer(), QWindowsAudioSource::bytesReady(), QSctpSocketPrivate::canReadNotification(), QRingChunk::capacity(), QWindowsFontEngine::capHeight(), QTlsPrivate::X509CertificateOpenSSL::certificatesFromPem(), QPicturePrivate::checkFormat(), QODBCDriverPrivate::checkUnicode(), childKeysOrGroups(), QTlsPrivate::TlsKeyGeneric::clear(), QXcbConnection::clientLeader(), QZipWriter::close(), QTlsPrivate::TlsCryptographSchannel::continueHandshake(), QWindowsMimeText::convertFromMime(), convertParticleData(), convertToExtendedType(), QXcbWindow::create(), QD3D11Buffer::create(), QD3D11RenderBuffer::create(), QD3D11Texture::create(), QD3D11GraphicsPipeline::create(), QD3D11ComputePipeline::create(), QFileSystemEngine::createDirectory(), QT_BEGIN_NAMESPACE::VertexBufferDataExt::createEntries(), QSSGMesh::Mesh::createLightmapUVChannel(), QSslContext::createSsl(), QtWaylandClient::QWaylandDataSource::data_source_send(), debugBinaryString(), QDtls::decryptDatagram(), QDtlsPrivateOpenSSL::decryptDatagram(), QTlsPrivate::TlsKeyGeneric::derFromPem(), QNetworkReplyWasmImplPrivate::doSendRequest(), QPdfEngine::drawHyperlink(), QV4::Moth::dumpBytecode(), dumpErrorInformation(), encodeEntity(), encodeFileName(), QRhiGles2::enqueueSubresUpload(), QRhiMetal::enqueueSubresUpload(), escapedString(), QWidget::event(), QDB2Result::exec(), QMYSQLResult::exec(), QODBCResult::exec(), QSQLiteResult::exec(), QOCICols::execBatch(), extractServiceData(), QXcbClipboardMime::formats_sys(), QDB2Driver::formatValue(), QMYSQLDriver::formatValue(), QODBCDriver::formatValue(), QPSQLDriver::formatValue(), QSqlDriver::formatValue(), QAudioBuffer::frameCount(), RingBuffer::freeBytes(), QBitArray::fromBits(), QJsonDocument::fromJson(), QString::fromLatin1(), QUrl::fromPercentEncoding(), QSSGMesh::Mesh::fromRuntimeData(), QmlTypesCreator::generate(), Moc::generate(), QHttpNetworkReplyPrivate::getChunkSize(), QWindowsFontEngine::getCMap(), QNfcTagType4NdefFsm::getCommand(), QQuick3DParticleInstanceTable::getInstanceBuffer(), QLocationUtils::getNmeaTime(), QXcbDrag::handleSelectionRequest(), QTlsPrivate::TlsCryptographSchannel::hasUndecryptedData(), QWaylandInputMethodEventBuilder::indexToWayland(), QGeoFileTileCache::isTileBogus(), QTextureFileData::isValid(), QIODevicePrivate::isWriteChunkCached(), QXcbKeyboard::keymapFromCore(), QOpenGLProgramBinaryCache::load(), QSvgIOHandlerPrivate::load(), QFontEngine::loadKerningPairs(), QSSGLoadedTexture::loadTextureData(), macValue(), QMemoryVideoBuffer::map(), nameToOSType(), normalizeType(), QJsonPrivate::Writer::objectToJson(), QIBaseDriver::open(), QODBCDriver::open(), operator+=(), operator<<(), RCCResourceLibrary::output(), QEdidParser::parse(), QTlsPrivate::X509CertificateGeneric::parse(), Preprocessor::parseDefineArguments(), QAuthenticatorPrivate::parseDigestAuthenticationChallenge(), patchQtCore(), QRhiD3D11::pipelineCacheData(), QRhiGles2::pipelineCacheData(), QRhiMetal::pipelineCacheData(), QByteDataBuffer::popFront(), QXcbXSettingsPrivate::populateSettings(), QODBCResult::prepare(), QRhiVulkan::prepareUploadSubres(), prepend(), Scanner::process(), QFontEngine::processHheaTable(), processSentence(), QOpenGLDebugLogger::pushGroup(), q_fromPercentEncoding(), QTlsPrivate::Q_GLOBAL_STATIC_WITH_ARGS(), qCreatev2Hash(), qEncodeNtlmv2Response(), QTest::qPrintDataTags(), qt_string_SQLSetConnectAttr(), qtValue(), rawBytes(), QAstcHandler::read(), QPkmHandler::read(), QPulseAudioSource::read(), QWindowsAudioSource::read(), QByteDataBuffer::read(), QImageReader::read(), QByteDataBuffer::read(), RingBuffer::readBytes(), QHttpPartPrivate::readData(), QHttpMultiPartIODevice::readData(), QHttpNetworkReplyPrivate::readHeader(), QOCICols::readPiecewise(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkReplyPrivate::readStatus(), QSGCompressedAtlasTexture::Texture::removedFromAtlas(), QVideoWindowPrivate::render(), QODBCResult::reset(), QBitArray::resize(), QMainWindowLayoutState::restoreState(), QInternalMimeData::retrieveData(), QXcbClipboardMime::retrieveData_sys(), QDnsLookupRunnable::run(), QQmlJSShadowCheck::run(), QQmlJSCodeGenerator::run(), QQmlJSBasicBlocks::run(), QQmlJSTypePropagator::run(), scanLangEnv(), QNearFieldTargetPrivateImpl::sendCommand(), HciManager::sendCommand(), QHttpProtocolHandler::sendRequest(), set_text(), setMatrix(), QByteArrayMatcher::setPattern(), QRhiGles2::setPipelineCacheData(), QWasmAudioOutput::setSource(), QSSGRhiShaderPipeline::setUniform(), QSSGRhiShaderPipeline::setUniformArray(), QXcbWindow::setWindowIconText(), QXcbWindow::setWindowTitle(), QHttpPartPrivate::size(), QQmlFile::size(), QNonContiguousByteDeviceByteArrayImpl::size(), QHttpMultiPartIODevice::size(), QConcatenable< QByteArray >::size(), QSGCompressedAtlasTexture::Texture::sizeInBytes(), QQuick3DParticleInstanceTable::sort(), QV4::RuntimeHelpers::stringToNumber(), QRhiMetal::subresUploadByteSize(), QRhiVulkan::subresUploadByteSize(), QWindowsFontDatabaseBase::EmbeddedFont::tableDirectoryEntry(), QTimeZonePrivate::territory(), toBase64(), QAsn1Element::toDateTime(), QIcc::toIccProfile(), QAsn1Element::toInteger(), QAsn1Element::toObjectId(), QAsn1Element::toString(), QTest::toString(), QTest::toString(), QWaylandInputMethodEventBuilder::trimmedIndexFromWayland(), QLockFilePrivate::tryLock_sys(), ClipWindow::updateClipboard(), QXcbClipboardTransaction::updateIncrementalProperty(), QQuick3DTextureData::updateSpatialNode(), QtWaylandClient::QWaylandTextInputv1::updateState(), QtWaylandClient::QWaylandTextInputv2::updateState(), QtWaylandClient::QWaylandTextInputv3::updateState(), QSSGQmlUtilities::valueToQml(), QDtlsClientVerifier::verifyClient(), QDtlsClientVerifierOpenSSL::verifyClient(), QSSGShaderDefaultMaterialKey::StringVisitor::visit(), TestHTTPServer::wait(), winIso639LangName(), wrapInFunction(), RingBuffer::write(), QICNSHandler::write(), QTiffHandler::write(), QWebpHandler::write(), QAsn1Element::write(), write_icc_profile(), QIBaseResultPrivate::writeBlob(), QLowEnergyControllerPrivateAndroid::writeCharacteristic(), QFFmpeg::AudioSourceIO::writeData(), RCCFileInfo::writeDataBlob(), QDtlsPrivateOpenSSL::writeDatagramEncrypted(), QLowEnergyControllerPrivateAndroid::writeDescriptor(), QPNGImageWriter::writeImage(), writeInstanceTable(), QSSGMesh::MeshInternal::writeMeshData(), QNearFieldTargetPrivateImpl::writeNdefMessages(), QSSGQmlUtilities::writeNodeProperties(), and QtWaylandClient::QWaylandPrimarySelectionSourceV1::zwp_primary_selection_source_v1_send().

◆ slice() [1/2]

QByteArray & QByteArray::slice ( qsizetype pos)
inline
Since
6.8 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Modifies this byte array to start at position pos, extending to its end, and returns a reference to this byte array.

Note
The behavior is undefined if pos < 0 or pos > size().
See also
sliced(), first(), last(), chopped(), chop(), truncate()

Definition at line 242 of file qbytearray.h.

References pos, and remove().

Referenced by wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ slice() [2/2]

QByteArray & QByteArray::slice ( qsizetype pos,
qsizetype n )
inline
Since
6.8

Modifies this byte array to start at position pos, extending for n bytes, and returns a reference to this byte array.

Note
The behavior is undefined if pos < 0, n < 0, or pos + n > size().

Example:

QByteArray x = "Five pineapples"_ba;
x.slice(5); // x == "pineapples"
x.slice(4, 3); // x == "app"
See also
sliced(), first(), last(), chopped(), chop(), truncate()

Definition at line 244 of file qbytearray.h.

References pos, remove(), and resize().

+ Here is the call graph for this function:

◆ sliced() [1/4]

QByteArray QByteArray::sliced ( qsizetype pos) &&
inline

Definition at line 215 of file qbytearray.h.

References pos.

◆ sliced() [2/4]

QByteArray QByteArray::sliced ( qsizetype pos) const &
inline

Definition at line 200 of file qbytearray.h.

References pos.

Referenced by QtBluezPeripheralDescriptor::QtBluezPeripheralDescriptor(), QRingChunk::toByteArray(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ sliced() [3/4]

QByteArray QByteArray::sliced ( qsizetype pos,
qsizetype n ) &&
inline

Definition at line 217 of file qbytearray.h.

References pos.

◆ sliced() [4/4]

QByteArray QByteArray::sliced ( qsizetype pos,
qsizetype n ) const &
inline

Definition at line 202 of file qbytearray.h.

References d, pos, and QByteArray().

+ Here is the call graph for this function:

◆ 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 2624 of file qbytearray.cpp.

References QList< T >::append(), end(), indexOf(), list, mid(), and sep.

Referenced by QOpenGLExtensionMatcher::QOpenGLExtensionMatcher(), QGuiApplicationPrivate::createPlatformIntegration(), QKmsDevice::createScreenForConnector(), gradleBuildFlags(), QWaylandCompositorPrivate::loadClientBufferIntegration(), QPlatformOpenGLContext::parseOpenGLVersion(), read_xpm_body(), readGradleProperties(), setMatrix(), QQuickShaderEffectPrivate::setMesh(), QOpenXRGraphicsVulkan::setupGraphics(), and QGenericUnixTheme::themeNames().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ 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 642 of file qbytearray.h.

References capacity(), d, and QArrayData::KeepSize.

Referenced by QMimeMagicRule::QMimeMagicRule().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ startsWith() [1/2]

bool QByteArray::startsWith ( char c) 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 this byte array starts with byte ch; otherwise returns false.

Definition at line 225 of file qbytearray.h.

◆ startsWith() [2/2]

bool QByteArray::startsWith ( QByteArrayView bv) const
inline
Since
6.0

Returns true if this byte array starts with the sequence of bytes viewed by bv; otherwise returns false.

Example:

QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
...
See also
endsWith(), first()

Definition at line 223 of file qbytearray.h.

References qToByteArrayViewIgnoringNull(), and QtPrivate::startsWith().

Referenced by QMimeMagicRule::QMimeMagicRule(), QFileSystemEngine::absoluteName(), QAstcHandler::canRead(), QKtxHandler::canRead(), QPkmHandler::canRead(), QGuiApplicationPrivate::createPlatformIntegration(), QFreetypeFace::getFace(), make_user_path_without_qstandard_paths(), QPlatformOpenGLContext::parseOpenGLVersion(), qtValue(), QHttpNetworkReplyPrivate::readStatus(), and dom::DataTransfer::setDataFromMimeData().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ swap()

void QByteArray::swap ( QByteArray & other)
inlinenoexcept
Since
4.8

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

Definition at line 104 of file qbytearray.h.

References d, and other().

Referenced by QAsn1Element::read(), remove(), QByteArray::FromBase64Result::swap(), and QRingChunk::swap().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toBase64()

QByteArray QByteArray::toBase64 ( Base64Options options = Base64Encoding) const
Since
5.2

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

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

The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.

See also
fromBase64()

Definition at line 4110 of file qbytearray.cpp.

References Base64UrlEncoding, data(), i, j, OmitTrailingEquals, out, Q_ASSERT, size(), truncate(), and Qt::Uninitialized.

Referenced by QAuthenticatorPrivate::calculateResponse(), main(), operator<<(), QWasmWindow::setWindowIcon(), and QQuickCanvasItem::toDataURL().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toDouble()

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

Returns the byte array converted to a double value.

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

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

QByteArray string("1234.56");
bool ok;
double a = string.toDouble(&ok); // a == 1234.56, ok == true
string = "1234.56 Volt";
a = str.toDouble(&ok); // a == 0, ok == false
Warning
The QByteArray content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.
Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.

This function ignores leading and trailing whitespace.

See also
number()

Definition at line 4044 of file qbytearray.cpp.

References ok, and QByteArrayView::toDouble().

Referenced by parseXftDpi(), and toFloat().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toFloat()

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

Returns the byte array converted to a float value.

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

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

QByteArray string("1234.56");
bool ok;
float a = string.toFloat(&ok); // a == 1234.56, ok == true
string = "1234.56 Volt";
a = str.toFloat(&ok); // a == 0, ok == false
Warning
The QByteArray content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.
Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.

This function ignores leading and trailing whitespace.

See also
number()

Definition at line 4083 of file qbytearray.cpp.

References QLocaleData::convertDoubleToFloat(), ok, and toDouble().

+ Here is the call graph for this function:

◆ toHex()

QByteArray QByteArray::toHex ( char separator = '\0') const

Returns a hex encoded copy of the byte array.

The hex encoding uses the numbers 0-9 and the letters a-f.

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

Example:

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

Definition at line 4700 of file qbytearray.cpp.

References QByteArray(), data(), hex, i, isEmpty(), o, QtMiscUtils::toHexLower(), and Qt::Uninitialized.

Referenced by bufferFromAttribute(), dumpAttributeVariant(), encodeFrame(), host_name_to_settings_key(), QMimeMagicRule::mask(), QQmlEngine::offlineStorageDatabaseFilePath(), writeAttribute(), QLowEnergyControllerPrivateAndroid::writeCharacteristic(), and QLowEnergyControllerPrivateAndroid::writeDescriptor().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toInt()

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

Returns the byte array converted to an int using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

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, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3860 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

Referenced by QDBusBlockingCallWatcher::QDBusBlockingCallWatcher(), QFontEngineFT::QFontEngineFT(), buildAndroidProject(), QSSGStageGeneratorBase::buildShaderSourcePass2(), QWindowsMimeHtml::convertToMime(), QNetworkReplyHttpImplPrivate::fetchCacheMetaData(), QSSGShaderKeyUnsigned< TBitWidth >::fromString(), QFreetypeFace::getFace(), parseXftInt(), QOpenSLESEngine::setAudioOutput(), and AndroidMediaPlayer::setAudioOutput().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toLong()

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

Returns the byte array converted to a long int using base base, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

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, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3923 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ toLongLong()

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

Returns the byte array converted to a {long long} using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3798 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ toLower() [1/2]

QByteArray QByteArray::toLower ( ) &&
inline

Definition at line 256 of file qbytearray.h.

◆ toLower() [2/2]

QByteArray QByteArray::toLower ( ) const &
inline

Definition at line 254 of file qbytearray.h.

Referenced by QPdfBookmarkModel::QPdfBookmarkModel(), QTextureFileReader::canRead(), QKmsDevice::createScreenForConnector(), formatByName(), QSSGInputUtil::getStreamForTextureFile(), QQmlXMLHttpRequest::header(), QWindowsOpengl32DLL::init(), QtWaylandClient::QWaylandXdgSurface::nativeResource(), QXcbNativeInterface::nativeResourceForBackingStore(), QXcbNativeInterface::nativeResourceForContext(), QQnxNativeInterface::nativeResourceForIntegration(), QXcbNativeInterface::nativeResourceForIntegration(), QtWaylandClient::QWaylandNativeInterface::nativeResourceForIntegration(), QOffscreenX11PlatformNativeInterface::nativeResourceForScreen(), QXcbNativeInterface::nativeResourceForScreen(), QtWaylandClient::QWaylandNativeInterface::nativeResourceForScreen(), QIOSIntegration::nativeResourceForWindow(), QtWaylandClient::QWaylandWlShellIntegration::nativeResourceForWindow(), QXcbNativeInterface::nativeResourceForWindow(), QtWaylandClient::QWaylandNativeInterface::nativeResourceForWindow(), QXcbNativeInterface::nativeResourceFunctionForBackingStore(), QXcbNativeInterface::nativeResourceFunctionForContext(), QCocoaNativeInterface::nativeResourceFunctionForIntegration(), QXcbNativeInterface::nativeResourceFunctionForIntegration(), QXcbNativeInterface::nativeResourceFunctionForScreen(), QXcbNativeInterface::nativeResourceFunctionForWindow(), QtWaylandClient::QWaylandNativeInterface::nativeResourceFunctionForWindow(), QNetworkCookiePrivate::parseSetCookieHeaderLine(), QXcbNativeInterface::platformFunction(), probeImageData(), read_xpm_body(), QHttpNetworkReplyPrivate::readHeader(), QPpmHandler::setOption(), wrapInFunction(), and QTextDocumentWriter::write().

+ Here is the caller graph for this function:

◆ toPercentEncoding()

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

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

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

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

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

Example:

QByteArray text = "{a fishy string?}";
QByteArray ba = text.toPercentEncoding("{}", "s");
qDebug("%s", ba.constData());
// 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 4859 of file qbytearray.cpp.

References QByteArray(), contains(), data(), isEmpty(), isNull(), length(), output, QtMiscUtils::toHexUpper(), and view.

+ Here is the call graph for this function:

◆ toShort()

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

Returns the byte array converted to a short using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3984 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ toStdString()

std::string QByteArray::toStdString ( ) const
Since
5.4

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

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

See also
fromStdString(), QString::toStdString()

Definition at line 4830 of file qbytearray.cpp.

References data().

Referenced by QWasmAudioInput::setAudioDevice(), QWasmAudioOutput::setSource(), and QWasmWindow::setWindowIcon().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toUInt()

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

Returns the byte array converted to an {unsigned int} using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3890 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

Referenced by QMimeMagicRule::QMimeMagicRule().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toULong()

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

Returns the byte array converted to an {unsigned long int} using base base, which is ten by default. Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3954 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ toULongLong()

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

Returns the byte array converted to an {unsigned long long} using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 3828 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

Referenced by QHttpNetworkHeaderPrivate::contentLength().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toUpper() [1/2]

QByteArray QByteArray::toUpper ( ) &&
inline

Definition at line 260 of file qbytearray.h.

◆ toUpper() [2/2]

QByteArray QByteArray::toUpper ( ) const &
inline

Definition at line 258 of file qbytearray.h.

Referenced by QDDSHandler::setOption(), and wrapInFunction().

+ Here is the caller graph for this function:

◆ toUShort()

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

Returns the byte array converted to an {unsigned short} using base base, which is ten by default.

Bases 0 and 2 through 36 are supported, using letters for digits beyond 9; A is ten, B is eleven and so on.

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 (base 16); otherwise, if it begins with "0b", it is assumed to be binary (base 2); otherwise, if it begins with "0", it is assumed to be octal (base 8); otherwise it is assumed to be decimal.

Returns 0 if the conversion fails.

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

Note
The conversion of the number is performed in the default C locale, regardless of the user's locale. Use QLocale to perform locale-aware conversions between numbers and strings.
Support for the "0b" prefix was added in Qt 6.4.
See also
number()

Definition at line 4014 of file qbytearray.cpp.

References base, ok, and qToByteArrayViewIgnoringNull().

+ Here is the call graph for this function:

◆ trimmed() [1/2]

QByteArray QByteArray::trimmed ( ) &&
inline

Definition at line 264 of file qbytearray.h.

◆ trimmed() [2/2]

◆ truncate()

void QByteArray::truncate ( qsizetype pos)

Truncates the byte array at index position pos.

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

Example:

QByteArray ba("Stockholm");
ba.truncate(5); // ba == "Stock"
See also
chop(), resize(), first()

Definition at line 1707 of file qbytearray.cpp.

References pos, and resize().

Referenced by QUtf8::convertFromUnicode(), QUtf32::convertFromUnicode(), QZipReader::fileData(), leftJustified(), QIBaseDriver::open(), q_fromPercentEncoding(), QTlsPrivate::Q_GLOBAL_STATIC_WITH_ARGS(), qDBusParametersForMethod(), qDecodeDataUrl(), QHttpNetworkReplyPrivate::readStatus(), rightJustified(), set_text(), toBase64(), and wrapInFunction().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Friends And Related Symbol Documentation

◆ ::tst_QByteArray

friend class ::tst_QByteArray
friend

Definition at line 66 of file qbytearray.h.

◆ comparesEqual [1/4]

Q_CORE_EXPORT bool comparesEqual ( const QByteArray & lhs,
char16_t rhs )
friend

Definition at line 6754 of file qstring.cpp.

◆ comparesEqual [2/4]

bool comparesEqual ( const QByteArray & lhs,
const QByteArrayView & rhs )
friend

Definition at line 511 of file qbytearray.h.

◆ comparesEqual [3/4]

Q_CORE_EXPORT bool comparesEqual ( const QByteArray & lhs,
const QChar & rhs )
friend

Definition at line 6743 of file qstring.cpp.

◆ comparesEqual [4/4]

bool comparesEqual ( const QByteArray & lhs,
std::nullptr_t  )
friend

Definition at line 538 of file qbytearray.h.

◆ compareThreeWay [1/4]

Q_CORE_EXPORT Qt::strong_ordering compareThreeWay ( const QByteArray & lhs,
char16_t rhs )
friend

Definition at line 6759 of file qstring.cpp.

◆ compareThreeWay [2/4]

Qt::strong_ordering compareThreeWay ( const QByteArray & lhs,
const QByteArrayView & rhs )
friend

Definition at line 514 of file qbytearray.h.

◆ compareThreeWay [3/4]

Q_CORE_EXPORT Qt::strong_ordering compareThreeWay ( const QByteArray & lhs,
const QChar & rhs )
friend

Definition at line 6748 of file qstring.cpp.

◆ compareThreeWay [4/4]

Qt::strong_ordering compareThreeWay ( const QByteArray & lhs,
std::nullptr_t  )
friend

Definition at line 540 of file qbytearray.h.

◆ data()

char * data ( )
related

\macro QT_NO_CAST_FROM_BYTEARRAY

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

See also
QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII

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 you can access following the returned pointer is size() + 1, including the '\0' terminator.

Example:

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

pointer-invalidation-desc

For read-only access, constData() is faster because it never causes a \l{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";
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 206 of file qopengles2ext.h.

◆ erase() [1/2]

template< typename T > qsizetype erase ( QByteArray & ba,
const T & t )
related
Since
6.1

Removes all elements that compare equal to t from the byte array ba. Returns the number of elements removed, if any.

See also
erase_if

Definition at line 782 of file qbytearray.h.

◆ erase [2/2]

template<typename T >
template< typename T > qsizetype erase ( QByteArray & ba,
const T & t )
friend
Since
6.1

Removes all elements that compare equal to t from the byte array ba. Returns the number of elements removed, if any.

See also
erase_if

Definition at line 782 of file qbytearray.h.

◆ erase_if() [1/2]

template< typename Predicate > qsizetype erase_if ( QByteArray & ba,
Predicate pred )
related
Since
6.1

Removes all elements for which the predicate pred returns true from the byte array ba. Returns the number of elements removed, if any.

See also
erase

Definition at line 788 of file qbytearray.h.

◆ erase_if [2/2]

template<typename Predicate >
template< typename Predicate > qsizetype erase_if ( QByteArray & ba,
Predicate pred )
friend
Since
6.1

Removes all elements for which the predicate pred returns true from the byte array ba. Returns the number of elements removed, if any.

See also
erase

Definition at line 788 of file qbytearray.h.

◆ operator""_ba()

operator""_ba ( const char * str,
size_t size )
related

\macro QByteArrayLiteral(ba)

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

For instance:

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

See also
QStringLiteral
Since
6.4

Literal operator that creates a QByteArray out of the first size characters in the char string literal str.

The QByteArray is created at compile time, and the generated string data is stored in the read-only segment of the compiled object file. Duplicate literals may share the same read-only memory. This functionality is interchangeable with QByteArrayLiteral, but saves typing when many string literals are present in the code.

The following code creates a QByteArray:

auto str = "hello"_ba;
QString str
[2]
See also
Qt::Literals::StringLiterals

Definition at line 805 of file qbytearray.h.

References QByteArray(), and str.

+ Here is the call graph for this function:

◆ operator+() [1/5]

QByteArray operator+ ( 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 byte a1 and byte array a2.

Definition at line 684 of file qbytearray.h.

References a1, a2, and QByteArray().

+ Here is the call graph for this function:

◆ operator+() [2/5]

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 '\0'-terminated string a1 and byte array a2.

Definition at line 682 of file qbytearray.h.

References a1, a2, and QByteArray().

+ Here is the call graph for this function:

◆ operator+() [3/5]

QByteArray operator+ ( const QByteArray & a1,
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 byte a2.

Definition at line 678 of file qbytearray.h.

References a1, a2, and QByteArray().

+ Here is the call graph for this function:

◆ operator+() [4/5]

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 '\0'-terminated string a2.

Definition at line 674 of file qbytearray.h.

References a1, a2, and QByteArray().

+ Here is the call graph for this function:

◆ operator+() [5/5]

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 670 of file qbytearray.h.

References a1, a2, and QByteArray().

+ Here is the call graph for this function:

◆ 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 3345 of file qbytearray.cpp.

References ba, constData(), isNull(), out, and size().

+ Here is the call graph for this function:

◆ 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 3362 of file qbytearray.cpp.

References ba, blockSize, clear(), data(), QByteArray(), qMin(), and resize().

+ Here is the call graph for this function:

◆ qChecksum()

quint16 qChecksum ( QByteArrayView data,
Qt::ChecksumType standard )
related
Since
5.9

Returns the CRC-16 checksum of data.

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

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

Definition at line 469 of file qbytearray.cpp.

References Qt::ChecksumIso3309, Qt::ChecksumItuV41, and crc_tbl.

◆ 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(const QByteArray &data)

Definition at line 728 of file qbytearray.h.

References qCompress().

+ Here is the call graph for this function:

◆ qCompress() [2/2]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Compresses the first nbytes of data at compression level compressionLevel and returns the compressed data in a new byte array.

Definition at line 671 of file qbytearray.cpp.

References capacity, Compression, dataIsNull(), deflate(), QArrayData::Grow, HeaderSize, lengthIsNegative(), out, QByteArray(), qToBigEndian(), tooMuchData(), and xxflate().

+ Here is the call graph for this function:

◆ qsnprintf()

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

\target bytearray-qsnprintf

A portable snprintf() function, calls qvsnprintf.

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

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

Definition at line 82 of file qvsnprintf.cpp.

References fmt, qvsnprintf(), ret, and str.

+ Here is the call graph for this function:

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

If both strings are \nullptr, they are deemed equal; otherwise, if either is \nullptr, it is treated as less than the other (even if the other is an empty string).

See also
qstrncmp(), qstricmp(), qstrnicmp(), {Character Case}, QByteArray::compare()

Definition at line 187 of file qbytearray.cpp.

◆ 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 \nullptr, it immediately returns \nullptr.

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

Note
If dst and src overlap, the behavior is undefined.
See also
qstrncpy()

Definition at line 101 of file qbytearray.cpp.

◆ 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 \nullptr, it immediately returns \nullptr.

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

Definition at line 79 of file qbytearray.cpp.

References qstrcpy().

+ Here is the call graph for this function:

◆ qstricmp()

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

A safe stricmp() function.

Compares str1 and str2, ignoring differences in the case of any ASCII characters.

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.

If both strings are \nullptr, they are deemed equal; otherwise, if either is \nullptr, it is treated as less than the other (even if the other is an empty string).

See also
qstrcmp(), qstrncmp(), qstrnicmp(), {Character Case}, QByteArray::compare()

Definition at line 232 of file qbytearray.cpp.

References QtMiscUtils::caseCompareAscii(), forever, Q_ASSERT, qCountLeadingZeroBits(), qCountTrailingZeroBits(), s2, and zero.

+ Here is the call graph for this function:

◆ QString

friend class QString
friend

Definition at line 588 of file qbytearray.h.

◆ qstrlen()

size_t qstrlen ( const char * str)
related

A safe strlen() function.

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

See also
qstrnlen()

Definition at line 104 of file qbytearrayalgorithms.h.

References QT_WARNING_DISABLE_GCC, QT_WARNING_POP, QT_WARNING_PUSH, and str.

Referenced by QByteArray().

+ Here is the caller graph for this function:

◆ qstrncmp()

int qstrncmp ( const char * str1,
const char * str2,
size_t 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.

If both strings are \nullptr, they are deemed equal; otherwise, if either is \nullptr, it is treated as less than the other (even if the other is an empty string or len is 0).

See also
qstrcmp(), qstricmp(), qstrnicmp(), {Character Case}, QByteArray::compare()

Definition at line 130 of file qbytearrayalgorithms.h.

◆ qstrncpy()

char * qstrncpy ( char * dst,
const char * src,
size_t 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. Guarantees that dst is '\0'-terminated, except when dst is \nullptr or len is 0. If src is \nullptr, returns \nullptr, otherwise returns dst.

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

Note
If dst and src overlap, the behavior is undefined.
Unlike strncpy(), this function does not write '\0' to all len bytes of dst, but stops after the terminating '\0'. In this sense, it's similar to C11's strncpy_s().
See also
qstrcpy()

Definition at line 138 of file qbytearray.cpp.

◆ qstrnicmp()

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

A safe strnicmp() function.

Compares at most len bytes of str1 and str2, ignoring differences in the case of any ASCII characters.

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.

If both strings are \nullptr, they are deemed equal; otherwise, if either is \nullptr, it is treated as less than the other (even if the other is an empty string or len is 0).

See also
qstrcmp(), qstrncmp(), qstricmp(), {Character Case}, QByteArray::compare()

Definition at line 322 of file qbytearray.cpp.

References QtMiscUtils::caseCompareAscii(), s1, and s2.

+ Here is the call graph for this function:

◆ qstrnlen()

size_t qstrnlen ( const char * str,
size_t 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 \nullptr, returns 0.

See also
qstrlen()

Definition at line 116 of file qbytearrayalgorithms.h.

References str.

◆ qUncompress() [1/3]

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. This number is just a hint for the initial size of the output buffer size, though. If the indicated size is too small to hold the result, the output buffer size will still be increased until either the output fits or the system runs out of memory. So, despite the 32-bit header, this function, on 64-bit platforms, can produce more than 4GiB of output.

Note
In Qt versions prior to Qt 6.5, more than 2GiB of data worked unreliably; in Qt versions prior to Qt 6.0, not at all.
See also
qCompress()

Definition at line 730 of file qbytearray.h.

References qUncompress().

+ Here is the call graph for this function:

◆ qUncompress() [2/3]

QByteArray qUncompress ( const uchar * data,
qsizetype nbytes )
related

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data.

Definition at line 763 of file qbytearray.cpp.

◆ qUncompress [3/3]

QByteArray qUncompress ( const uchar * data,
qsizetype nbytes )
friend

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Uncompresses the first nbytes of data and returns a new byte array with the uncompressed data.

Definition at line 763 of file qbytearray.cpp.

◆ qvsnprintf()

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

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

Definition at line 37 of file qvsnprintf.cpp.

References ba, constData(), fmt, length(), qMin(), str, and QString::vasprintf().

+ Here is the call graph for this function:

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