QByteArray 类

QByteArray 类提供字节数组。 更多...

头: #include <QByteArray>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

注意: 此类的所有函数 可重入 .

公共类型

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

公共函数

QByteArray ()
QByteArray (const char * data , qsizetype size = -1)
QByteArray (qsizetype size , char ch )
QByteArray (qsizetype size , Qt::Initialization)
QByteArray (const QByteArray & other )
QByteArray (QByteArray && other )
~QByteArray ()
QByteArray & append (const QByteArray & ba )
QByteArray & append (char ch )
QByteArray & append (qsizetype count , char ch )
QByteArray & append (const char * str )
QByteArray & append (const char * str , qsizetype len )
QByteArray & append (QByteArrayView data )
(从 6.6 起) QByteArray & assign (QByteArrayView v )
(从 6.6 起) QByteArray & assign (qsizetype n , char c )
(从 6.6 起) QByteArray & assign (InputIterator first , InputIterator last )
char at (qsizetype i ) const
char back () const
char & back ()
QByteArray::iterator begin ()
QByteArray::const_iterator begin () const
qsizetype capacity () const
QByteArray::const_iterator cbegin () const
QByteArray::const_iterator cend () const
void chop (qsizetype n )
QByteArray chopped (qsizetype len ) const &
QByteArray chopped (qsizetype len ) &&
void clear ()
(从 6.0 起) int compare (QByteArrayView bv , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QByteArray::const_iterator constBegin () const
const char * constData () const
QByteArray::const_iterator constEnd () const
(从 6.0 起) bool contains (QByteArrayView bv ) const
bool contains (char ch ) const
(从 6.0 起) qsizetype count (QByteArrayView bv ) const
qsizetype count (char ch ) const
QByteArray::const_reverse_iterator crbegin () const
QByteArray::const_reverse_iterator crend () const
char * data ()
const char * data () const
QByteArray::iterator end ()
QByteArray::const_iterator end () const
(从 6.0 起) bool endsWith (QByteArrayView bv ) const
bool endsWith (char ch ) const
(since 6.1) QByteArray::iterator erase (QByteArray::const_iterator first , QByteArray::const_iterator last )
(从 6.5 起) QByteArray::iterator erase (QByteArray::const_iterator it )
QByteArray & fill (char ch , qsizetype size = -1)
(从 6.0 起) QByteArray first (qsizetype n ) const &
(从 6.0 起) QByteArray first (qsizetype n ) &&
char front () const
char & front ()
(从 6.0 起) qsizetype indexOf (QByteArrayView bv , qsizetype from = 0) const
qsizetype indexOf (char ch , qsizetype from = 0) const
(从 6.0 起) QByteArray & insert (qsizetype i , QByteArrayView data )
QByteArray & insert (qsizetype i , const char * s )
QByteArray & insert (qsizetype i , const QByteArray & data )
QByteArray & insert (qsizetype i , qsizetype count , char ch )
QByteArray & insert (qsizetype i , char ch )
QByteArray & insert (qsizetype i , const char * data , qsizetype len )
bool isEmpty () const
bool isLower () const
bool isNull () const
bool isUpper () const
(since 6.3) bool isValidUtf8 () const
(从 6.0 起) QByteArray last (qsizetype n ) const &
(从 6.0 起) QByteArray last (qsizetype n ) &&
(从 6.0 起) qsizetype lastIndexOf (QByteArrayView bv , qsizetype from ) const
qsizetype lastIndexOf (char ch , qsizetype from = -1) const
(从 6.2 起) qsizetype lastIndexOf (QByteArrayView bv ) const
QByteArray left (qsizetype len ) const &
QByteArray left (qsizetype len ) &&
QByteArray leftJustified (qsizetype width , char fill = ' ', bool truncate = false) const
qsizetype length () const
QByteArray mid (qsizetype pos , qsizetype len = -1) const &
QByteArray mid (qsizetype pos , qsizetype len = -1) &&
(从 6.4 起) QByteArray percentDecoded (char percent = '%') const
QByteArray & prepend (QByteArrayView ba )
QByteArray & prepend (char ch )
QByteArray & prepend (qsizetype count , char ch )
QByteArray & prepend (const char * str )
QByteArray & prepend (const char * str , qsizetype len )
QByteArray & prepend (const QByteArray & ba )
void push_back (const QByteArray & other )
void push_back (char ch )
void push_back (const char * str )
(从 6.0 起) void push_back (QByteArrayView str )
void push_front (const QByteArray & other )
void push_front (char ch )
void push_front (const char * str )
(从 6.0 起) void push_front (QByteArrayView str )
QByteArray::reverse_iterator rbegin ()
QByteArray::const_reverse_iterator rbegin () const
QByteArray & remove (qsizetype pos , qsizetype len )
(从 6.5 起) QByteArray & removeAt (qsizetype pos )
(从 6.5 起) QByteArray & removeFirst ()
(since 6.1) QByteArray & removeIf (Predicate pred )
(从 6.5 起) QByteArray & removeLast ()
QByteArray::reverse_iterator rend ()
QByteArray::const_reverse_iterator rend () const
QByteArray repeated (qsizetype times ) const
QByteArray & replace (qsizetype pos , qsizetype len , QByteArrayView after )
QByteArray & replace (qsizetype pos , qsizetype len , const char * after , qsizetype alen )
QByteArray & replace (char before , QByteArrayView after )
QByteArray & replace (const char * before , qsizetype bsize , const char * after , qsizetype asize )
(从 6.0 起) QByteArray & replace (QByteArrayView before , QByteArrayView after )
QByteArray & replace (char before , char after )
void reserve (qsizetype size )
void resize (qsizetype size )
(从 6.4 起) void resize (qsizetype newSize , char c )
QByteArray right (qsizetype len ) const &
QByteArray right (qsizetype len ) &&
QByteArray rightJustified (qsizetype width , char fill = ' ', bool truncate = false) const
QByteArray & setNum (int n , int base = 10)
QByteArray & setNum (short n , int base = 10)
QByteArray & setNum (ushort n , int base = 10)
QByteArray & setNum (uint n , int base = 10)
QByteArray & setNum (long n , int base = 10)
QByteArray & setNum (ulong n , int base = 10)
QByteArray & setNum (qlonglong n , int base = 10)
QByteArray & setNum (qulonglong n , int base = 10)
QByteArray & setNum (float n , char format = 'g', int precision = 6)
QByteArray & setNum (double n , char format = 'g', int precision = 6)
QByteArray & setRawData (const char * data , qsizetype size )
void shrink_to_fit ()
QByteArray simplified () const
qsizetype size () const
(从 6.0 起) QByteArray sliced (qsizetype pos , qsizetype n ) const &
(从 6.0 起) QByteArray sliced (qsizetype pos ) const &
(从 6.0 起) QByteArray sliced (qsizetype pos ) &&
(从 6.0 起) QByteArray sliced (qsizetype pos , qsizetype n ) &&
QList<QByteArray> split (char sep ) const
void squeeze ()
(从 6.0 起) bool startsWith (QByteArrayView bv ) const
bool startsWith (char ch ) const
void swap (QByteArray & other )
QByteArray toBase64 (QByteArray::Base64Options options = Base64Encoding) const
CFDataRef toCFData () const
double toDouble (bool * ok = nullptr) const
(从 6.5 起) emscripten::val toEcmaUint8Array ()
float toFloat (bool * ok = nullptr) const
QByteArray toHex (char separator = '\0') const
int toInt (bool * ok = nullptr, int base = 10) const
long toLong (bool * ok = nullptr, int base = 10) const
qlonglong toLongLong (bool * ok = nullptr, int base = 10) const
QByteArray toLower () const
NSData * toNSData () const
QByteArray toPercentEncoding (const QByteArray & exclude = QByteArray(), const QByteArray & 包括 = QByteArray(), char percent = '%') const
CFDataRef toRawCFData () const
NSData * toRawNSData () const
short toShort (bool * ok = nullptr, int base = 10) const
std::string toStdString () const
uint toUInt (bool * ok = nullptr, int base = 10) const
ulong toULong (bool * ok = nullptr, int base = 10) const
qulonglong toULongLong (bool * ok = nullptr, int base = 10) const
ushort toUShort (bool * ok = nullptr, int base = 10) const
QByteArray toUpper () const
QByteArray trimmed () const
void truncate (qsizetype pos )
const char * operator const char * () const
const void * operator const void * () const
bool operator!= (const QString & str ) const
QByteArray & operator+= (const QByteArray & ba )
QByteArray & operator+= (char ch )
QByteArray & operator+= (const char * str )
bool operator< (const QString & str ) const
bool operator<= (const QString & str ) const
QByteArray & operator= (const QByteArray & other )
QByteArray & operator= (const char * str )
QByteArray & operator= (QByteArray && other )
bool operator== (const QString & str ) const
bool operator> (const QString & str ) const
bool operator>= (const QString & str ) const
char & operator[] (qsizetype i )
char operator[] (qsizetype i ) const

静态公共成员

QByteArray fromBase64 (const QByteArray & base64 , QByteArray::Base64Options options = Base64Encoding)
QByteArray::FromBase64Result fromBase64Encoding (QByteArray && base64 , QByteArray::Base64Options options = Base64Encoding)
QByteArray::FromBase64Result fromBase64Encoding (const QByteArray & base64 , QByteArray::Base64Options options = Base64Encoding)
QByteArray fromCFData (CFDataRef data )
(从 6.5 起) QByteArray fromEcmaUint8Array (emscripten::val uint8array )
QByteArray fromHex (const QByteArray & hexEncoded )
QByteArray fromNSData (const NSData * data )
QByteArray fromPercentEncoding (const QByteArray & input , char percent = '%')
QByteArray fromRawCFData (CFDataRef data )
QByteArray fromRawData (const char * data , qsizetype size )
QByteArray fromRawNSData (const NSData * data )
QByteArray fromStdString (const std::string & str )
QByteArray number (int n , int base = 10)
QByteArray number (uint n , int base = 10)
QByteArray number (long n , int base = 10)
QByteArray number (ulong n , int base = 10)
QByteArray number (qlonglong n , int base = 10)
QByteArray number (qulonglong n , int base = 10)
QByteArray number (double n , char format = 'g', int precision = 6)
(since 6.1) qsizetype erase (QByteArray & ba , const T & t )
(since 6.1) qsizetype erase_if (QByteArray & ba , Predicate pred )
quint16 qChecksum (QByteArrayView data , Qt::ChecksumType standard = Qt::ChecksumIso3309)
QByteArray qCompress (const QByteArray & data , int compressionLevel = -1)
QByteArray qCompress (const uchar * data , qsizetype nbytes , int compressionLevel = -1)
QByteArray qUncompress (const QByteArray & data )
QByteArray qUncompress (const uchar * data , qsizetype nbytes )
int qsnprintf (char * str , size_t n , const char * fmt , ...)
int qstrcmp (const char * str1 , const char * str2 )
char * qstrcpy (char * dst , const char * src )
char * qstrdup (const char * src )
int qstricmp (const char * str1 , const char * str2 )
size_t qstrlen (const char * str )
int qstrncmp (const char * str1 , const char * str2 , size_t len )
char * qstrncpy (char * dst , const char * src , size_t len )
int qstrnicmp (const char * str1 , const char * str2 , size_t len )
size_t qstrnlen (const char * str , size_t maxlen )
int qvsnprintf (char * str , size_t n , const char * fmt , va_list ap )
bool operator!= (const QByteArray & a1 , const QByteArray & a2 )
bool operator!= (const QByteArray & a1 , const char * a2 )
bool operator!= (const char * a1 , const QByteArray & a2 )
(从 6.4 起) QByteArray operator""_ba (const char * str , size_t size )
QByteArray operator+ (const QByteArray & a1 , const QByteArray & a2 )
QByteArray operator+ (const QByteArray & a1 , const char * a2 )
QByteArray operator+ (const QByteArray & a1 , char a2 )
QByteArray operator+ (const char * a1 , const QByteArray & a2 )
QByteArray operator+ (char a1 , const QByteArray & a2 )
bool operator< (const QByteArray & a1 , const QByteArray & a2 )
bool operator< (const QByteArray & a1 , const char * a2 )
bool operator< (const char * a1 , const QByteArray & a2 )
QDataStream & operator<< (QDataStream & out , const QByteArray & ba )
bool operator<= (const QByteArray & a1 , const QByteArray & a2 )
bool operator<= (const QByteArray & a1 , const char * a2 )
bool operator<= (const char * a1 , const QByteArray & a2 )
bool operator== (const QByteArray & a1 , const QByteArray & a2 )
bool operator== (const QByteArray & a1 , const char * a2 )
bool operator== (const char * a1 , const QByteArray & a2 )
bool operator> (const QByteArray & a1 , const QByteArray & a2 )
bool operator> (const QByteArray & a1 , const char * a2 )
bool operator> (const char * a1 , const QByteArray & a2 )
bool operator>= (const QByteArray & a1 , const QByteArray & a2 )
bool operator>= (const QByteArray & a1 , const char * a2 )
bool operator>= (const char * a1 , const QByteArray & a2 )
QDataStream & operator>> (QDataStream & in , QByteArray & ba )

QByteArrayLiteral ( ba )
QT_NO_CAST_FROM_BYTEARRAY

详细描述

QByteArray 可以被用于存储原生字节 (包括 \0) 和传统 8 位以 \0 结尾的字符串。使用 QByteArray 更方便比使用 const char * 。在幕后,它始终确保数据之后紧跟 \0 终止符,并使用 隐式共享 (写入时拷贝) 以缩减内存用量并避免不必要的数据拷贝。

除 QByteArray 外,Qt 还提供 QString 类以存储字符串数据。对于大多数目的, 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 * 到其构造函数。例如,以下代码创建包含数据 Hello 大小为 5 的字节数组:

QByteArray ba("Hello");
					

尽管 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:

QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
					

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

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

at () can be faster than operator[](), because it never causes a 深拷贝 的出现。

要每次提取多个字节,使用 first (), last (),或 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'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
					

If you want to obtain the length of the data up to and excluding the first '\0' 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 () 或 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 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 (),和 remove ()。例如:

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

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 () 函数可能很慢 ( 线性时间 ) 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 隐式共享 .

QByteArray provides STL 样式迭代器 ( QByteArray::const_iterator and QByteArray::iterator ). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.

注意: Iterators and references to individual QByteArray elements are subject to stability issues. They are often invalidated when a QByteArray-modifying operation (e.g. insert () 或 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 () 或 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:

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

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.

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:

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

所有函数除了 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 ().

最大尺寸和内存不足情况

The maximum size of QByteArray depends on the architecture. Most 64-bit systems can allocate more than 2 GB of memory, with a typical limit of 2^63 bytes. The actual value also depends on the overhead required for managing the data block. As a result, you can expect the maximum size of 2 GB minus overhead on 32-bit platforms, and 2^63 bytes minus overhead on 64-bit platforms. The number of elements that can be stored in a QByteArray is this maximum size.

When memory allocation fails, QByteArray throws a std::bad_alloc exception if the application is being compiled with exception support. Out of memory conditions in Qt containers are the only case where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.

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

C 区域设置和 ASCII 函数

QByteArray generally handles data as bytes, without presuming any semantics; where it does presume semantics, it uses the C locale and ASCII encoding. Standard Unicode encodings are supported by QString , other encodings may be supported using QStringEncoder and QStringDecoder to convert to Unicode. For locale-specific interpretation of text, use QLocale or QString .

C Strings

Traditional C strings, also known as '\0'-terminated strings, are sequences of bytes, specified by a start-point and implicitly including each byte up to, but not including, the first '\0' byte thereafter. Methods that accept such a pointer, without a length, will interpret it as this sequence of bytes. Such a sequence, by construction, cannot contain a '\0' byte.

Other overloads accept a start-pointer and a byte-count; these use the given number of bytes, following the start address, regardless of whether any of them happen to be '\0' bytes. In some cases, where there is no overload taking only a pointer, passing a length of -1 will cause the method to use the offset of the first '\0' byte after the pointer as the length; a length of -1 should only be passed if the method explicitly says it does this (in which case it is typically a default argument).

Spacing Characters

A frequent requirement is to remove spacing characters from a byte array ( '\n' , '\t' , ' ' , etc.). If you want to remove spacing from both ends of a QByteArray, use trimmed (). If you want to also replace each run of spacing characters with a single space character within the byte array, use simplified (). Only ASCII spacing characters are recognized for these purposes.

数字字符串转换

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

Character Case

In QByteArray, the notion of uppercase and lowercase and of case-independent comparison is limited to ASCII. Non-ASCII characters are treated as caseless, since their case depends on encoding. This affects functions that support a case insensitive option or that change the case of their arguments. Functions that this affects include compare (), isLower (), isUpper (), toLower () 和 toUpper ().

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

另请参阅 QByteArrayView , QString ,和 QBitArray .

成员类型文档编制

enum QByteArray:: Base64Option
flags QByteArray:: Base64Options

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

常量 描述
QByteArray::Base64Encoding 0 (default) The regular Base64 alphabet, called simply "base64"
QByteArray::Base64UrlEncoding 1 An alternate alphabet, called "base64url", which replaces two characters in the alphabet to be more friendly to URLs.
QByteArray::KeepTrailingEquals 0 (default) Keeps the trailing padding equal signs at the end of the encoded data, so the data is always a size multiple of four.
QByteArray::OmitTrailingEquals 2 Omits adding the padding equal signs at the end of the encoded data.
QByteArray::IgnoreBase64DecodingErrors 0 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.
QByteArray::AbortOnBase64DecodingErrors 4 When decoding Base64-encoded data, stops at the first decoding error. This enum value has been added in Qt 5.15.

QByteArray::fromBase64Encoding () 和 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.

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

QByteArray:: const_iterator

此 typedef 提供 STL 样式 const 迭代器为 QByteArray .

另请参阅 QByteArray::const_reverse_iterator and QByteArray::iterator .

QByteArray:: const_reverse_iterator

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

另请参阅 QByteArray::reverse_iterator and QByteArray::const_iterator .

QByteArray:: iterator

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

另请参阅 QByteArray::reverse_iterator and QByteArray::const_iterator .

QByteArray:: reverse_iterator

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

另请参阅 QByteArray::const_reverse_iterator and QByteArray::iterator .

成员函数文档编制

const char *QByteArray:: operator const char * () const

const void *QByteArray:: operator const void * () const

注意: 使用 constData () 取而代之在新代码中。

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.

指针仍然有效只要不发生分离和 QByteArray 不被修改。

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

可以禁用此运算符通过定义 QT_NO_CAST_FROM_BYTEARRAY 当编译应用程序时。

注意: QByteArray 可以存储任何字节值 (包括 \0),但大多数函数需要 char * 自变量,假定数据在遇到首个 \0 时结束。

另请参阅 constData ().

QByteArray QByteArray:: left ( qsizetype len ) &&

QByteArray QByteArray:: left ( qsizetype len ) const &

Returns a byte array that contains the first len 字节对于此字节数组。

若知道 len 不可以超出边界,使用 first () 代替在新代码中,因为它更快。

返回整个字节数组若 len 大于 size ().

返回空 QByteArray if len < 0。

另请参阅 first (), last (), startsWith (), chopped (), chop (),和 truncate ().

QByteArray QByteArray:: right ( qsizetype len ) &&

返回的字节数组包含最后 len 字节对于此字节数组。

若知道 len 不可以超出边界,使用 last () 代替在新代码中,因为它更快。

返回整个字节数组若 len 大于 size ().

返回空 QByteArray if len < 0。

另请参阅 endsWith (), last (), first (), sliced (), chopped (), chop (),和 truncate ().

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

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

返回的字节数组包含 len 字节从此字节数组,起始于位置 pos .

若知道 pos and len 不可以超出边界,使用 sliced () 代替在新代码中,因为它更快。

len 为 -1 (默认),或 pos + len >= size (), returns a byte array containing all bytes starting at position pos until the end of the byte array.

另请参阅 first (), last (), sliced (), chopped (), chop (),和 truncate ().

[since 6.0] QByteArray QByteArray:: first ( qsizetype n ) &&

[since 6.0] QByteArray QByteArray:: first ( qsizetype n ) const &

返回第一 n bytes of the byte array.

注意: 行为未定义当 n < 0 or n > size ().

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 last (), sliced (), startsWith (), chopped (), chop (),和 truncate ().

[since 6.0] QByteArray QByteArray:: last ( qsizetype n ) &&

[since 6.0] QByteArray QByteArray:: last ( qsizetype n ) const &

Returns the last n bytes of the byte array.

注意: 行为未定义当 n < 0 or n > size ().

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 first (), sliced (), endsWith (), chopped (), chop (),和 truncate ().

[since 6.0] QByteArray QByteArray:: sliced ( qsizetype pos , qsizetype n ) &&

[since 6.0] QByteArray QByteArray:: sliced ( qsizetype pos , qsizetype n ) const &

Returns a byte array containing the n bytes of this object starting at position pos .

注意: 行为未定义当 pos < 0, n < 0, or pos + n > size ().

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 first (), last (), chopped (), chop (),和 truncate ().

[since 6.0] QByteArray QByteArray:: sliced ( qsizetype pos ) &&

[since 6.0] QByteArray QByteArray:: sliced ( qsizetype pos ) const &

这是重载函数。

Returns a byte array containing the bytes starting at position pos in this object, and extending to the end of this object.

注意: 行为未定义当 pos < 0 or pos > size ().

该函数在 Qt 6.0 引入。

另请参阅 first (), last (), sliced (), chopped (), chop (),和 truncate ().

QByteArray QByteArray:: chopped ( qsizetype len ) &&

QByteArray QByteArray:: chopped ( qsizetype len ) const &

返回的字节数组包含最左 size () - len 字节对于此字节数组。

注意: 行为未定义若 len 为负或大于 size ().

另请参阅 endsWith (), first (), last (), sliced (), chop (),和 truncate ().

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

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

这是重载函数。

Decodes the Base64 array base64 , using the options defined by options 。若 options 包含 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 包含 AbortOnBase64DecodingErrors , then decoding will stop at the first invalid character.

例如:

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

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

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

另请参阅 toBase64 ().

[constexpr noexcept] QByteArray:: QByteArray ()

构造空字节数组。

另请参阅 isEmpty ().

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

构造字节数组包含前 size 字节的数组 data .

data 为 0,构造 null 字节数组。

size 为负, data 假定指向以 \0 结尾的字符串,并动态确定其长度。

QByteArray 制作字符串数据的深拷贝。

另请参阅 fromRawData ().

QByteArray:: QByteArray ( qsizetype size , char ch )

构造字节数组大小为 size 采用将每字节设为 ch .

另请参阅 fill ().

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

构造字节数组大小为 size 具有未初始化内容。

[noexcept] QByteArray:: QByteArray (const QByteArray & other )

构造副本为 other .

此操作花费 常量时间 ,因为 QByteArray 隐式共享 . This makes returning a QByteArray from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), taking 线性时间 .

另请参阅 operator= ().

[noexcept] QByteArray:: QByteArray ( QByteArray && other )

移动构造 QByteArray 实例,使之指向同一对象如 other 所指向的。

[noexcept] QByteArray:: ~QByteArray ()

销毁字节数组。

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

追加字节数组 ba 到此字节数组的末尾。

范例:

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

这如同 insert( size (), ba ).

注意: QByteArray 隐式共享 类。因此,若追加到空字节数组,那么字节数组将仅仅共享的数据保持在 ba 。在这种情况下,不进行数据拷贝,花费 常量时间 。若共享实例被修改,它将被拷贝 (写时拷贝),花费 线性时间 .

若要追加到的字节数组非空,履行数据深拷贝,花费 线性时间 .

append() 函数通常非常快 ( 常量时间 ),因为 QByteArray 预分配额外空间在数据末尾,所以它可以增长无需每次重新分配整个数组。

另请参阅 operator+= (), prepend (),和 insert ().

QByteArray &QByteArray:: append ( char ch )

这是重载函数。

追加字节 ch 到此字节数组。

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

这是重载函数。

追加 count 拷贝的字节 ch 到此字节数组,并返回此字节数组的引用。

count 为负 (或 0),什么都不会追加到字节数组。

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

这是重载函数。

追加以 \0 结尾的字符串 str 到此字节数组。

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

这是重载函数。

追加第一 len 字节起始于 str to this byte array and returns a reference to this byte array. The bytes appended may include '\0' bytes.

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

len 为 0 或 str is null, nothing is appended to the byte array. Ensure that len is not longer than str .

QByteArray &QByteArray:: append ( QByteArrayView data )

这是重载函数。

追加 data 到此字节数组。

[since 6.6] QByteArray &QByteArray:: assign ( QByteArrayView v )

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.

该函数在 Qt 6.6 引入。

[since 6.6] QByteArray &QByteArray:: assign ( qsizetype n , char c )

Replaces the contents of this byte array with n 个副本对于 c and returns a reference to this byte array.

The size of this byte array will be equal to n ,必须非负。

此函数将只分配内存若 n exceeds the capacity of this byte array or this byte array is shared.

该函数在 Qt 6.6 引入。

另请参阅 fill ().

[since 6.6] template <typename InputIterator, QByteArray::if_input_iterator<InputIterator> = true> QByteArray &QByteArray:: assign ( InputIterator first , InputIterator last )

Replaces the contents of this byte array with a copy of the elements in the iterator range [ first , last ) and returns a reference to this byte array.

The size of this byte array will be equal to the number of elements in the range [ first , last ).

This function will only allocate memory if the number of elements in the range exceeds the capacity of this byte array or this byte array is shared.

注意: This function overload only participates in overload resolution if InputIterator meets the requirements of a LegacyInputIterator .

注意: The behavior is undefined if either argument is an iterator into *this or [ first , last ) is not a valid range.

该函数在 Qt 6.6 引入。

char QByteArray:: at ( qsizetype i ) const

返回字节按索引位置 i 在字节数组中。

i 必须是字节数组中的有效索引位置 (即 0 <= i < size ()).

另请参阅 operator[] ().

char QByteArray:: back () const

返回字节数组中的最后一个字节。如同 at(size() - 1) .

此函数为兼容 STL (标准模板库) 提供。

警告: 空字节数组调用此函数,会构成未定义行为。

另请参阅 front (), at (),和 operator[] ().

char &QByteArray:: back ()

返回字节数组中的最后一个字节的引用。如同 operator[](size() - 1) .

此函数为兼容 STL (标准模板库) 提供。

警告: 空字节数组调用此函数,会构成未定义行为。

另请参阅 front (), at (),和 operator[] ().

QByteArray::iterator QByteArray:: begin ()

返回 STL 样式迭代器 指向字节数组第一字节。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 constBegin () 和 end ().

[noexcept] QByteArray::const_iterator QByteArray:: begin () const

此函数重载 begin()。

qsizetype QByteArray:: capacity () const

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

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

注意: 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.

另请参阅 reserve () 和 squeeze ().

[noexcept] QByteArray::const_iterator QByteArray:: cbegin () const

返回常量 STL 样式迭代器 指向字节数组第一字节。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 begin () 和 cend ().

[noexcept] QByteArray::const_iterator QByteArray:: cend () const

返回常量 STL 样式迭代器 指向字节数组中仅仅最后字节之后。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 cbegin () 和 end ().

void QByteArray:: chop ( qsizetype n )

移除 n bytes from the end of the byte array.

n 大于 size (), the result is an empty byte array.

范例:

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

另请参阅 truncate (), resize (),和 first ().

void QByteArray:: clear ()

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

另请参阅 resize () 和 isNull ().

[noexcept, since 6.0] int QByteArray:: compare ( QByteArrayView bv , Qt::CaseSensitivity cs = Qt::CaseSensitive) const

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

该函数在 Qt 6.0 引入。

另请参阅 operator== and Character Case .

[noexcept] QByteArray::const_iterator QByteArray:: constBegin () const

返回常量 STL 样式迭代器 指向字节数组第一字节。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 begin () 和 constEnd ().

[noexcept] const char *QByteArray:: constData () const

返回以字节数组形式存储的 const 数据指针。指针可以用于访问组成数组的字节。数据以 \0 结尾,除非 QByteArray 对象是从原生数据创建的。

指针仍然有效只要不发生分离和 QByteArray 不被修改。

此函数主要用于将字节数组传递给的函数接受 const char * .

注意: QByteArray 可以存储任何字节值 (包括 \0),但大多数函数需要 char * 自变量,假定数据在遇到首个 \0 时结束。

另请参阅 data (), operator[] (),和 fromRawData ().

[noexcept] QByteArray::const_iterator QByteArray:: constEnd () const

返回常量 STL 样式迭代器 指向字节数组中仅仅最后字节之后。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 constBegin () 和 end ().

[since 6.0] bool QByteArray:: contains ( QByteArrayView bv ) const

返回 true 若此字节数组包含出现的字节序列,查看通过 bv ;否则返回 false .

该函数在 Qt 6.0 引入。

另请参阅 indexOf () 和 count ().

bool QByteArray:: contains ( char ch ) const

这是重载函数。

返回 true 若字节数组包含字节 ch ;否则返回 false .

[since 6.0] qsizetype QByteArray:: count ( QByteArrayView bv ) const

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

该函数在 Qt 6.0 引入。

另请参阅 contains () 和 indexOf ().

qsizetype QByteArray:: count ( char ch ) const

这是重载函数。

Returns the number of occurrences of byte ch 在字节数组中。

另请参阅 contains () 和 indexOf ().

[noexcept] QByteArray::const_reverse_iterator QByteArray:: crbegin () const

返回常量 STL-style reverse iterator pointing to the first byte in the byte-array, in reverse order.

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 begin (), rbegin (),和 rend ().

[noexcept] QByteArray::const_reverse_iterator QByteArray:: crend () const

返回常量 STL-style reverse iterator pointing just after the last byte in the byte-array, in reverse order.

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 end (), rend (),和 rbegin ().

char *QByteArray:: data ()

返回以字节数组形式存储的数据指针。指针可以用于访问和修改组成数组的字节。数据以 \0 结尾,即指针返回后可以访问的字节数是只要没有发生分离并且 xx 指针保持有效 size () + 1,包括 \0 终止符。

范例:

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

指针仍然有效只要不发生分离和 QByteArray 不被修改。

对于只读访问, constData () 更快,因为它从不导致 深拷贝 的出现。

此函数主要用于将字节数组传递给的函数接受 const char * .

以下范例制作由 data() 返回的 char* 副本,但会破坏堆并导致崩溃,因为它没有为末尾 \0 分配字节:

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

这个分配了正确的空间数量:

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

注意: QByteArray 可以存储任何字节值 (包括 \0),但大多数函数需要 char * 自变量,假定数据在遇到首个 \0 时结束。

另请参阅 constData () 和 operator[] ().

[noexcept] const char *QByteArray:: data () const

这是重载函数。

QByteArray::iterator QByteArray:: end ()

返回 STL 样式迭代器 指向字节数组中仅仅最后字节之后。

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 begin () 和 constEnd ().

[noexcept] QByteArray::const_iterator QByteArray:: end () const

此函数重载 end()。

[since 6.0] bool QByteArray:: endsWith ( QByteArrayView bv ) const

返回 true 若此字节数组的结尾为字节视图序列 bv ;否则返回 false .

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 startsWith () 和 last ().

bool QByteArray:: endsWith ( char ch ) const

这是重载函数。

返回 true if this byte array ends with byte ch ;否则返回 false .

[since 6.1] QByteArray::iterator QByteArray:: erase ( QByteArray::const_iterator first , QByteArray::const_iterator last )

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.

该函数在 Qt 6.1 引入。

[since 6.5] QByteArray::iterator QByteArray:: erase ( QByteArray::const_iterator it )

移除表示字符 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"
					

该函数在 Qt 6.5 引入。

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

Sets every byte in the byte array to ch 。若 size is different from -1 (the default), the byte array is resized to size size 事先。

范例:

QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"
ba.fill('X', 2);
// ba == "XX"
					

另请参阅 resize ().

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

Returns a decoded copy of the Base64 array base64 , using the options defined by options 。若 options 包含 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 包含 AbortOnBase64DecodingErrors , then decoding will stop at the first invalid character.

例如:

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 RFC 4648 .

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

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

另请参阅 toBase64 () 和 fromBase64Encoding ().

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

构造新的 QByteArray containing a copy of the CFData data .

另请参阅 fromRawCFData (), fromRawData (), toRawCFData (),和 toCFData ().

[static, since 6.5] QByteArray QByteArray:: fromEcmaUint8Array ( emscripten::val uint8array )

构造新的 QByteArray containing a copy of the Uint8Array uint8array .

This function transfers data from a JavaScript data buffer - which is not addressable from C++ code - to heap memory owned by a QByteArray . The Uint8Array can be released once this function returns and a copy has been made.

The uint8array argument must an emscripten::val referencing an Uint8Array object, e.g. obtained from a global JavaScript variable:

emscripten::val uint8array = emscripten::val::global("g_uint8array");
QByteArray byteArray = QByteArray::fromEcmaUint8Array(uint8array);
					

This function returns a null QByteArray if the size of the Uint8Array exceeds the maximum capacity of QByteArray , or if the uint8array argument is not of the Uint8Array type.

该函数在 Qt 6.5 引入。

另请参阅 toEcmaUint8Array ().

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

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

例如:

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

另请参阅 toHex ().

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

构造新的 QByteArray containing a copy of the NSData data .

另请参阅 fromRawNSData (), fromRawData (), toNSData (),和 toRawNSData ().

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

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

例如:

QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
qDebug("%s", text.data());      // reports "Qt is great!"
					

另请参阅 percentDecoded ().

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

构造 QByteArray that uses the bytes of the CFData data .

The data 的字节不拷贝。

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

另请参阅 fromCFData (), fromRawData (), toRawCFData (),和 toCFData ().

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

构造 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 隐式共享 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 未拥有所有权对于 data , so the QByteArray destructor will never delete the raw data , even when the last QByteArray referring to data 被销毁。

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

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

 static const char mydata[] = {
    '\x00', '\x00', '\x03', '\x84', '\x78', '\x9c', '\x3b', '\x76',
    '\xec', '\x18', '\xc3', '\x31', '\x0a', '\xf1', '\xcc', '\x99',
    ...
    '\x6d', '\x5b'
};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
					

警告: 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.

另请参阅 setRawData (), data (),和 constData ().

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

构造 QByteArray that uses the bytes of the NSData data .

The data 的字节不拷贝。

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

另请参阅 fromNSData (), fromRawData (), toRawNSData (),和 toNSData ().

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

返回副本为 str string as a QByteArray .

另请参阅 toStdString () 和 QString::fromStdString ().

char QByteArray:: front () const

返回字节数组中的第一个字节。如同 at(0) .

此函数为兼容 STL (标准模板库) 提供。

警告: 空字节数组调用此函数,会构成未定义行为。

另请参阅 back (), at (),和 operator[] ().

char &QByteArray:: front ()

返回字节数组中的第一个字节的引用。如同 operator[](0) .

此函数为兼容 STL (标准模板库) 提供。

警告: 空字节数组调用此函数,会构成未定义行为。

另请参阅 back (), at (),和 operator[] ().

[since 6.0] qsizetype QByteArray:: indexOf ( QByteArrayView bv , qsizetype from = 0) const

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.

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 lastIndexOf (), contains (),和 count ().

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

这是重载函数。

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.

范例:

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
					

另请参阅 lastIndexOf () 和 contains ().

[since 6.0] QByteArray &QByteArray:: insert ( qsizetype i , QByteArrayView data )

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

范例:

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

For large byte arrays, this operation can be slow ( 线性时间 ), because it requires moving all the bytes at indexes i and above by at least one position further in memory.

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 .

该函数在 Qt 6.0 引入。

另请参阅 append (), prepend (), replace (),和 remove ().

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

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

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 .

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

另请参阅 append (), prepend (), replace (),和 remove ().

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

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

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 .

另请参阅 append (), prepend (), replace (),和 remove ().

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

这是重载函数。

插入 count 拷贝的字节 ch at index position i 在字节数组中。

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 .

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

这是重载函数。

Inserts byte ch at index position i 在字节数组中。

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 .

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

这是重载函数。

插入 len bytes, starting at data , at position i 在字节数组中。

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 .

[noexcept] bool QByteArray:: isEmpty () const

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

范例:

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

另请参阅 size ().

bool QByteArray:: isLower () const

返回 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.

另请参阅 isUpper () 和 toLower ().

[noexcept] bool QByteArray:: isNull () const

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

范例:

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

另请参阅 isEmpty ().

bool QByteArray:: isUpper () const

返回 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.

另请参阅 isLower () 和 toUpper ().

[noexcept, since 6.3] bool QByteArray:: isValidUtf8 () const

返回 true if this byte array contains valid UTF-8 encoded data, or false 否则。

该函数在 Qt 6.3 引入。

[since 6.0] qsizetype QByteArray:: lastIndexOf ( QByteArrayView bv , qsizetype from ) const

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 .

from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.

Returns -1 if no match is found.

范例:

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

注意: 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.

该函数在 Qt 6.0 引入。

另请参阅 indexOf (), contains (),和 count ().

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

这是重载函数。

Returns the index position of the start of the last occurrence of byte ch in this byte array, searching backward from index position from 。若 from is -1 (the default), the search starts at the last byte (at index size () - 1). Returns -1 if no match is found.

范例:

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
					

另请参阅 indexOf () 和 contains ().

[since 6.2] qsizetype QByteArray:: lastIndexOf ( QByteArrayView bv ) const

这是重载函数。

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.

范例:

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

该函数在 Qt 6.2 引入。

另请参阅 indexOf (), contains (),和 count ().

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.

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.

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.

范例:

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

另请参阅 rightJustified ().

[noexcept] qsizetype QByteArray:: length () const

如同 size ().

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

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

Returns a byte array containing a string representing n ,使用指定 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.

范例:

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

注意: 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.

另请参阅 setNum () 和 toInt ().

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

这是重载函数。

另请参阅 toUInt ().

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

这是重载函数。

另请参阅 toLong ().

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

这是重载函数。

另请参阅 toULong ().

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

这是重载函数。

另请参阅 toLongLong ().

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

这是重载函数。

另请参阅 toULongLong ().

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

这是重载函数。

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 QString::number (double, char, int). For example:

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

另请参阅 toDouble () 和 QLocale::FloatingPointPrecisionOption .

[since 6.4] QByteArray QByteArray:: percentDecoded ( char percent = '%') const

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.

例如:

QByteArray encoded("Qt%20is%20great%33");
QByteArray decoded = encoded.percentDecoded(); // Set to "Qt is great!"
					

注意: 给定无效输入 (譬如:包含 %G5 序列的字符串,不是有效十六进制数字),输出也将无效。例如:%G5 序列可以解码为 W。

该函数在 Qt 6.4 引入。

另请参阅 toPercentEncoding () 和 QUrl::fromPercentEncoding ().

QByteArray &QByteArray:: prepend ( QByteArrayView ba )

Prepends the byte array view ba 到此字节数组,并返回此字节数组的引用。

This operation is typically very fast ( 常量时间 ),因为 QByteArray preallocates extra space at the beginning of the data, so it can grow without reallocating the entire array each time.

范例:

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

这如同 insert(0, ba ).

另请参阅 append () 和 insert ().

QByteArray &QByteArray:: prepend ( char ch )

这是重载函数。

Prepends the byte ch 到此字节数组。

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

这是重载函数。

前置 count 拷贝的字节 ch 到此字节数组。

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

这是重载函数。

Prepends the '\0'-terminated string str 到此字节数组。

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

这是重载函数。

前置 len 字节起始于 str to this byte array. The bytes prepended may include '\0' bytes.

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

这是重载函数。

前置 ba 到此字节数组。

void QByteArray:: push_back (const QByteArray & other )

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

void QByteArray:: push_back ( char ch )

这是重载函数。

如同 append( ch ).

void QByteArray:: push_back (const char * str )

这是重载函数。

如同 append( str ).

[since 6.0] void QByteArray:: push_back ( QByteArrayView str )

这是重载函数。

如同 append( str ).

该函数在 Qt 6.0 引入。

void QByteArray:: push_front (const QByteArray & other )

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

void QByteArray:: push_front ( char ch )

这是重载函数。

如同 prepend( ch ).

void QByteArray:: push_front (const char * str )

这是重载函数。

如同 prepend( str ).

[since 6.0] void QByteArray:: push_front ( QByteArrayView str )

这是重载函数。

如同 prepend( str ).

该函数在 Qt 6.0 引入。

QByteArray::reverse_iterator QByteArray:: rbegin ()

返回 STL-style reverse iterator pointing to the first byte in the byte-array, in reverse order.

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 begin (), crbegin (),和 rend ().

[noexcept] QByteArray::const_reverse_iterator QByteArray:: rbegin () const

这是重载函数。

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

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

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 .

范例:

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.

另请参阅 insert (), replace (),和 squeeze ().

[since 6.5] QByteArray &QByteArray:: removeAt ( qsizetype pos )

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

该函数在 Qt 6.5 引入。

另请参阅 remove ().

[since 6.5] QByteArray &QByteArray:: removeFirst ()

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

该函数在 Qt 6.5 引入。

另请参阅 remove ().

[since 6.1] template <typename Predicate> QByteArray &QByteArray:: removeIf ( Predicate pred )

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

该函数在 Qt 6.1 引入。

另请参阅 remove ().

[since 6.5] QByteArray &QByteArray:: removeLast ()

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

该函数在 Qt 6.5 引入。

另请参阅 remove ().

QByteArray::reverse_iterator QByteArray:: rend ()

返回 STL-style reverse iterator pointing just after the last byte in the byte-array, in reverse order.

警告: 返回迭代器不验证当分离时或当 QByteArray 被修改。

另请参阅 end (), crend (),和 rbegin ().

[noexcept] QByteArray::const_reverse_iterator QByteArray:: rend () const

这是重载函数。

QByteArray QByteArray:: repeated ( qsizetype times ) const

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

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

范例:

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

QByteArray &QByteArray:: replace ( qsizetype pos , qsizetype len , QByteArrayView after )

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

范例:

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

另请参阅 insert () 和 remove ().

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

这是重载函数。

替换 len bytes from index position pos with alen bytes starting at position after . The bytes inserted may include '\0' bytes.

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

这是重载函数。

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

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

这是重载函数。

Replaces every occurrence of the bsize 字节起始于 before 采用 asize 字节起始于 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.

[since 6.0] QByteArray &QByteArray:: replace ( QByteArrayView before , QByteArrayView after )

这是重载函数。

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

范例:

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

该函数在 Qt 6.0 引入。

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

这是重载函数。

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

void QByteArray:: reserve ( qsizetype size )

试图分配内存为至少 size 字节。

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.

警告: 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.

另请参阅 squeeze () 和 capacity ().

void QByteArray:: resize ( qsizetype size )

把字节数组的尺寸设为 size 字节。

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.

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

注意: While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use squeeze ().

另请参阅 size (), truncate (),和 squeeze ().

[since 6.4] void QByteArray:: resize ( qsizetype newSize , char c )

把字节数组的尺寸设为 newSize 字节。

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 .

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

注意: While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use squeeze ().

该函数在 Qt 6.4 引入。

另请参阅 size (), truncate (),和 squeeze ().

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

Returns a byte array of size width 包含 fill byte followed by this byte array.

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.

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

范例:

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

另请参阅 leftJustified ().

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

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.

范例:

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

注意: 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.

另请参阅 number () 和 toInt ().

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

这是重载函数。

另请参阅 toShort ().

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

这是重载函数。

另请参阅 toUShort ().

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

这是重载函数。

另请参阅 toUInt ().

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

这是重载函数。

另请参阅 toLong ().

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

这是重载函数。

另请参阅 toULong ().

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

这是重载函数。

另请参阅 toLongLong ().

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

这是重载函数。

另请参阅 toULongLong ().

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

这是重载函数。

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 QString::number (double, char, int)), and returns a reference to this byte array.

另请参阅 toFloat ().

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

这是重载函数。

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 QString::number (double, char, int)), and returns a reference to this byte array.

另请参阅 toDouble () 和 QLocale::FloatingPointPrecisionOption .

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

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

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

另请参阅 fromRawData (), data (),和 constData ().

void QByteArray:: shrink_to_fit ()

此函数为兼容 STL (标准模板库) 提供。它相当于 squeeze ().

QByteArray QByteArray:: simplified () const

Returns a copy of this byte array that has spacing characters removed from the start and end, and in which each sequence of internal spacing characters is replaced with a single space.

The spacing characters are those for which the standard C++ isspace() 函数返回 true in the C locale; these are the ASCII characters tabulation '\t', line feed '\n', carriage return '\r', vertical tabulation '\v', form feed '\f', and space ' '.

范例:

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

另请参阅 trimmed (), QChar::SpecialCharacter ,和 Spacing Characters .

[noexcept] qsizetype QByteArray:: size () const

返回此字节数组的字节数。

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 () 和 constData () as arguments to functions that expect '\0'-terminated strings. If the QByteArray object was created from a raw data that didn't include the trailing '\0'-termination byte, then QByteArray doesn't add it automatically unless a 深拷贝 被创建。

范例:

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

另请参阅 isEmpty () 和 resize ().

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

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

void QByteArray:: squeeze ()

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

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

另请参阅 reserve () 和 capacity ().

[since 6.0] bool QByteArray:: startsWith ( QByteArrayView bv ) const

返回 true if this byte array starts with the sequence of bytes viewed by bv ;否则返回 false .

范例:

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

该函数在 Qt 6.0 引入。

另请参阅 endsWith () 和 first ().

bool QByteArray:: startsWith ( char ch ) const

这是重载函数。

返回 true 若此字节数组开头采用字节 ch ;否则返回 false .

[noexcept] void QByteArray:: swap ( QByteArray & other )

交换字节数组 other with this byte array. This operation is very fast and never fails.

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

返回字节数组的副本,编码使用选项 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 RFC 4648 .

另请参阅 fromBase64 ().

CFDataRef QByteArray:: toCFData () const

创建 CFData 从 QByteArray .

调用者拥有 CFData 对象并负责释放它。

另请参阅 toRawCFData (), fromCFData (), fromRawCFData (),和 fromRawData ().

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

返回字节数组被转换成 double 值。

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

ok 不是 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
					

警告: 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.

注意: 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.

此函数忽略前导和结尾空格。

另请参阅 number ().

[since 6.5] emscripten::val QByteArray:: toEcmaUint8Array ()

Creates a Uint8Array from a QByteArray .

This function transfers data from heap memory owned by a QByteArray to a JavaScript data buffer. The function allocates and copies into an ArrayBuffer, and returns a Uint8Array view to that buffer.

The JavaScript objects own a copy of the data, and this QByteArray can be safely deleted after the copy has been made.

QByteArray byteArray = "test";
emscripten::val uint8array = QByteArray::toEcmaUint8Array(byteArray);
					

该函数在 Qt 6.5 引入。

另请参阅 toEcmaUint8Array().

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

返回字节数组被转换成 float 值。

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

ok 不是 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
					

警告: 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.

注意: 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.

此函数忽略前导和结尾空格。

另请参阅 number ().

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.

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

范例:

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

另请参阅 fromHex ().

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

返回字节数组被转换成 int 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

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

返回字节数组被转换成 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

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

返回字节数组被转换成 long long 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

QByteArray QByteArray:: toLower () const

Returns a copy of the byte array in which each ASCII uppercase letter converted to lowercase.

范例:

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

另请参阅 isLower (), toUpper (),和 Character Case .

NSData *QByteArray:: toNSData () const

创建 NSData 从 QByteArray .

NSData 对象会被自动释放。

另请参阅 fromNSData (), fromRawNSData (), fromRawData (),和 toRawNSData ().

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

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

By default, this function will encode all 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 包括 percent character is always encoded.

范例:

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.

另请参阅 fromPercentEncoding () 和 QUrl::toPercentEncoding ().

CFDataRef QByteArray:: toRawCFData () const

Constructs a CFData that uses the bytes of the QByteArray .

The QByteArray 的字节不拷贝。

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

另请参阅 toCFData (), fromRawCFData (), fromCFData (),和 fromRawData ().

NSData *QByteArray:: toRawNSData () const

Constructs a NSData that uses the bytes of the QByteArray .

The QByteArray 的字节不拷贝。

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

另请参阅 fromRawNSData (), fromNSData (), fromRawData (),和 toNSData ().

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

返回字节数组被转换成 short 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

std::string QByteArray:: toStdString () const

返回 std::string 对象带有的数据包含在此 QByteArray .

此运算符主要用于传递 QByteArray 到接受 std::string 对象的函数。

另请参阅 fromStdString () 和 QString::toStdString ().

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

返回字节数组被转换成 无符号 int 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

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

返回字节数组被转换成 unsigned long int 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

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

返回字节数组被转换成 unsigned long long 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

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

返回字节数组被转换成 unsigned short 使用基 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.

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.

返回 0,若转换失败。

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

注意: 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.

注意: 在 Qt 6.4 添加对 0b 前缀的支持。

另请参阅 number ().

QByteArray QByteArray:: toUpper () const

Returns a copy of the byte array in which each ASCII lowercase letter converted to uppercase.

范例:

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

另请参阅 isUpper (), toLower (),和 Character Case .

QByteArray QByteArray:: trimmed () const

Returns a copy of this byte array with spacing characters removed from the start and end.

The spacing characters are those for which the standard C++ isspace() 函数返回 true in the C locale; these are the ASCII characters tabulation '\t', line feed '\n', carriage return '\r', vertical tabulation '\v', form feed '\f', and space ' '.

范例:

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

不像 simplified (),trimmed() 保持内部间距不变。

另请参阅 simplified (), QChar::SpecialCharacter ,和 Spacing Characters .

void QByteArray:: truncate ( qsizetype pos )

截取字节数组按索引位置 pos .

pos 超越数组末尾,什么都不发生。

范例:

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

另请参阅 chop (), resize (),和 first ().

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

返回 true 若此字节数组不等于 UTF-8 编码的 str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

追加字节数组 ba onto the end of this byte array and returns a reference to this byte array.

范例:

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

注意: QByteArray 隐式共享 类。因此,若追加到空字节数组,那么字节数组将仅仅共享的数据保持在 ba 。在这种情况下,不进行数据拷贝,花费 常量时间 。若共享实例被修改,它将被拷贝 (写时拷贝),花费 线性时间 .

若要追加到的字节数组非空,履行数据深拷贝,花费 线性时间 .

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.

另请参阅 append () 和 prepend ().

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

这是重载函数。

追加字节 ch onto the end of this byte array and returns a reference to this byte array.

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

这是重载函数。

追加以 \0 结尾的字符串 str onto the end of this byte array and returns a reference to this byte array.

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

返回 true if this byte array is lexically less than the UTF-8 encoding of str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返回 true if this byte array is lexically less than or equal to the UTF-8 encoding of str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

赋值 other 到此字节数组,并返回此字节数组的引用。

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

这是重载函数。

赋值 str 到此字节数组。

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

[noexcept] QByteArray &QByteArray:: operator= ( QByteArray && other )

移动赋值 other 到此 QByteArray 实例。

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

返回 true if this byte array is equal to the UTF-8 encoding of str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返回 true if this byte array is lexically greater than the UTF-8 encoding of str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返回 true if this byte array is greater than or equal to the UTF-8 encoding of str ;否则返回 false .

比较是区分大小写的。

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII 当编译应用程序时。那么需要调用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返回字节按索引位置 i 作为可修改引用。

i 必须是字节数组中的有效索引位置 (即 0 <= i < size ()).

范例:

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

另请参阅 at ().

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

这是重载函数。

如同 at( i ).

相关非成员

[since 6.1] template <typename T> qsizetype erase ( QByteArray & ba , const T & t )

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

该函数在 Qt 6.1 引入。

另请参阅 erase_if .

[since 6.1] template <typename Predicate> qsizetype erase_if ( QByteArray & ba , Predicate pred )

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

该函数在 Qt 6.1 引入。

另请参阅 erase .

quint16 qChecksum ( QByteArrayView data , Qt::ChecksumType standard = Qt::ChecksumIso3309)

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.

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

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

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

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

另请参阅 qUncompress (const QByteArray &data).

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

这是重载函数。

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 若输入数据被破坏。

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.

注意: 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.

注意: 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.

另请参阅 qCompress ().

QByteArray qUncompress (const uchar * data , qsizetype nbytes )

这是重载函数。

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

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

可移植 snprintf() 函数,调用 qvsnprintf。

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

警告: 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.

另请参阅 qvsnprintf () 和 QString::asprintf ().

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

安全 strcmp() 函数。

比较 str1 and str2 。返回负值若 str1 小于 str2 , 0 if str1 等于 str2 或正值若 str1 大于 str2 .

若两字符串为 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).

另请参阅 qstrncmp (), qstricmp (), qstrnicmp (), Character Case ,和 QByteArray::compare ().

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

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

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

注意: dst and src overlap, the behavior is undefined.

另请参阅 qstrncpy ().

char * qstrdup (const char * src )

返回复制字符串。

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

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

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

安全 stricmp() 函数。

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

Returns a negative value if str1 小于 str2 , 0 if str1 等于 str2 或正值若 str1 大于 str2 .

若两字符串为 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).

另请参阅 qstrcmp (), qstrncmp (), qstrnicmp (), Character Case ,和 QByteArray::compare ().

size_t qstrlen (const char * str )

安全 strlen() 函数。

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

另请参阅 qstrnlen ().

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

安全 strncmp() 函数。

比较最多 len bytes of str1 and str2 .

Returns a negative value if str1 小于 str2 , 0 if str1 等于 str2 或正值若 str1 大于 str2 .

若两字符串为 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).

另请参阅 qstrcmp (), qstricmp (), qstrnicmp (), Character Case ,和 QByteArray::compare ().

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

安全 strncpy() 函数。

拷贝最多 len 字节来自 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 ,返回 nullptr ,否则返回 dst .

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

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

另请参阅 qstrcpy ().

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

安全 strnicmp() 函数。

比较最多 len bytes of str1 and str2 , ignoring differences in the case of any ASCII characters.

Returns a negative value if str1 小于 str2 , 0 if str1 等于 str2 或正值若 str1 大于 str2 .

若两字符串为 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).

另请参阅 qstrcmp (), qstrncmp (), qstricmp (), Character Case ,和 QByteArray::compare ().

size_t qstrnlen (const char * str , size_t maxlen )

安全 strnlen() 函数。

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

另请参阅 qstrlen ().

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

可移植 vsnprintf() 函数。会调用 ::vsnprintf() , ::_vsnprintf() ,或 ::vsnprintf_s depending on the system, or fall back to an internal version.

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

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

警告: 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 () 代替。

另请参阅 qsnprintf () 和 QString::asprintf ().

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

这是重载函数。

返回 true 若字节数组 a1 不等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 不等于以 \0 结尾的字符串 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 不等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

[noexcept, since 6.4] QByteArray operator""_ba (const char * str , size_t size )

文字运算符创建的 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.

以下代码创建 QByteArray :

using namespace Qt::Literals::StringLiterals;
auto str = "hello"_ba;
					

该函数在 Qt 6.4 引入。

另请参阅 Qt::Literals::StringLiterals .

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

返回的字节数组结果是串联字节数组 a1 和字节数组 a2 .

另请参阅 QByteArray::operator+= ().

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

这是重载函数。

返回的字节数组结果是串联字节数组 a1 and '\0'-terminated string a2 .

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

这是重载函数。

返回的字节数组结果是串联字节数组 a1 and byte a2 .

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

这是重载函数。

Returns a byte array that is the result of concatenating '\0'-terminated string a1 和字节数组 a2 .

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

这是重载函数。

Returns a byte array that is the result of concatenating byte a1 和字节数组 a2 .

[noexcept] bool operator< (const QByteArray & a1 , const QByteArray & a2 )

这是重载函数。

返回 true 若字节数组 a1 词汇上小于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 is lexically less than the '\0'-terminated string a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 词汇上小于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

写入字节数组 ba 到流 out 并返回流引用。

另请参阅 序列化 Qt 数据类型 .

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

这是重载函数。

返回 true 若字节数组 a1 词法上 <= 字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 is lexically less than or equal to the '\0'-terminated string a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 词法上 <= 字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

[noexcept] bool operator== (const QByteArray & a1 , const QByteArray & a2 )

这是重载函数。

返回 true 若字节数组 a1 等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 等于以 \0 结尾的字符串 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

[noexcept] bool operator> (const QByteArray & a1 , const QByteArray & a2 )

这是重载函数。

返回 true 若字节数组 a1 词法上大于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 is lexically greater than the '\0'-terminated string a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 词法上大于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 词法上大于等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若字节数组 a1 is lexically greater than or equal to the '\0'-terminated string a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

这是重载函数。

返回 true 若以 \0 结尾的字符串 a1 词法上大于等于字节数组 a2 ;否则返回 false .

另请参阅 QByteArray::compare ().

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

读取字节数组到 ba 从流 in 并返回流引用。

另请参阅 序列化 Qt 数据类型 .

宏文档编制

QByteArrayLiteral ( ba )

宏生成数据为 QByteArray 从字符串文字 ba 在编译时。创建 QByteArray 是自由的在此情况下,且生成的字节数组数据是存储在编译对象文件的只读段中。

例如:

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

使用 QByteArrayLiteral 而不是带双引号的纯 C++ 字符串文字可以显著加速创建 QByteArray 实例从编译时的已知数据。

另请参阅 QStringLiteral .

QT_NO_CAST_FROM_BYTEARRAY

禁用自动转换从 QByteArray 到 const char * 或 const void *。

另请参阅 QT_NO_CAST_TO_ASCII and QT_NO_CAST_FROM_ASCII .