Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QByteArray Class

TheQByteArray class provides an array of bytes.More...

Header:#include <QByteArray>
Inherited By:

Q3CString

Note: All functions in this class arereentrant.

Public Functions

QByteArray()
QByteArray(const char * str)
QByteArray(const char * data, int size)
QByteArray(int size, char ch)
QByteArray(const QByteArray & other)
~QByteArray()
QByteArray &append(const QByteArray & ba)
QByteArray &append(const QString & str)
QByteArray &append(const char * str)
QByteArray &append(const char * str, int len)
QByteArray &append(char ch)
charat(int i) const
intcapacity() const
voidchop(int n)
voidclear()
const char *constData() const
boolcontains(const QByteArray & ba) const
boolcontains(const char * str) const
boolcontains(char ch) const
intcount(const QByteArray & ba) const
intcount(const char * str) const
intcount(char ch) const
intcount() const
char *data()
const char *data() const
boolendsWith(const QByteArray & ba) const
boolendsWith(const char * str) const
boolendsWith(char ch) const
QByteArray &fill(char ch, int size = -1)
intindexOf(const QByteArray & ba, int from = 0) const
intindexOf(const QString & str, int from = 0) const
intindexOf(const char * str, int from = 0) const
intindexOf(char ch, int from = 0) const
QByteArray &insert(int i, const QByteArray & ba)
QByteArray &insert(int i, const QString & str)
QByteArray &insert(int i, const char * str)
QByteArray &insert(int i, const char * str, int len)
QByteArray &insert(int i, char ch)
boolisEmpty() const
boolisNull() const
intlastIndexOf(const QByteArray & ba, int from = -1) const
intlastIndexOf(const QString & str, int from = -1) const
intlastIndexOf(const char * str, int from = -1) const
intlastIndexOf(char ch, int from = -1) const
QByteArrayleft(int len) const
QByteArrayleftJustified(int width, char fill = ' ', bool truncate = false) const
intlength() const
QByteArraymid(int pos, int len = -1) const
QByteArray &prepend(const QByteArray & ba)
QByteArray &prepend(const char * str)
QByteArray &prepend(const char * str, int len)
QByteArray &prepend(char ch)
voidpush_back(const QByteArray & other)
voidpush_back(const char * str)
voidpush_back(char ch)
voidpush_front(const QByteArray & other)
voidpush_front(const char * str)
voidpush_front(char ch)
QByteArray &remove(int pos, int len)
QByteArrayrepeated(int times) const
QByteArray &replace(int pos, int len, const QByteArray & after)
QByteArray &replace(int pos, int len, const char * after)
QByteArray &replace(int pos, int len, const char * after, int alen)
QByteArray &replace(const QByteArray & before, const QByteArray & after)
QByteArray &replace(const char * before, const QByteArray & after)
QByteArray &replace(const char * before, int bsize, const char * after, int asize)
QByteArray &replace(const QByteArray & before, const char * after)
QByteArray &replace(const QString & before, const QByteArray & after)
QByteArray &replace(const QString & before, const char * after)
QByteArray &replace(const char * before, const char * after)
QByteArray &replace(char before, const QByteArray & after)
QByteArray &replace(char before, const QString & after)
QByteArray &replace(char before, const char * after)
QByteArray &replace(char before, char after)
voidreserve(int size)
voidresize(int size)
QByteArrayright(int len) const
QByteArrayrightJustified(int width, char fill = ' ', bool truncate = false) const
QByteArray &setNum(int n, int base = 10)
QByteArray &setNum(uint n, int base = 10)
QByteArray &setNum(short n, int base = 10)
QByteArray &setNum(ushort n, int base = 10)
QByteArray &setNum(qlonglong n, int base = 10)
QByteArray &setNum(qulonglong n, int base = 10)
QByteArray &setNum(double n, char f = 'g', int prec = 6)
QByteArray &setNum(float n, char f = 'g', int prec = 6)
QByteArray &setRawData(const char * data, uint size)
QByteArraysimplified() const
intsize() const
QList<QByteArray>split(char sep) const
voidsqueeze()
boolstartsWith(const QByteArray & ba) const
boolstartsWith(const char * str) const
boolstartsWith(char ch) const
voidswap(QByteArray & other)
QByteArraytoBase64() const
doubletoDouble(bool * ok = 0) const
floattoFloat(bool * ok = 0) const
QByteArraytoHex() const
inttoInt(bool * ok = 0, int base = 10) const
longtoLong(bool * ok = 0, int base = 10) const
qlonglongtoLongLong(bool * ok = 0, int base = 10) const
QByteArraytoLower() const
QByteArraytoPercentEncoding(const QByteArray & exclude = QByteArray(), const QByteArray & include = QByteArray(), char percent = '%') const
shorttoShort(bool * ok = 0, int base = 10) const
uinttoUInt(bool * ok = 0, int base = 10) const
ulongtoULong(bool * ok = 0, int base = 10) const
qulonglongtoULongLong(bool * ok = 0, int base = 10) const
ushorttoUShort(bool * ok = 0, int base = 10) const
QByteArraytoUpper() const
QByteArraytrimmed() const
voidtruncate(int pos)
operator const char *() const
operator const void *() const
booloperator!=(const QString & str) const
QByteArray &operator+=(const QByteArray & ba)
QByteArray &operator+=(const QString & str)
QByteArray &operator+=(const char * str)
QByteArray &operator+=(char ch)
booloperator<(const QString & str) const
booloperator<=(const QString & str) const
QByteArray &operator=(const QByteArray & other)
QByteArray &operator=(QByteArray && other)
QByteArray &operator=(const char * str)
booloperator==(const QString & str) const
booloperator>(const QString & str) const
booloperator>=(const QString & str) const
QByteRefoperator[](int i)
charoperator[](int i) const
QByteRefoperator[](uint i)
charoperator[](uint i) const

Static Public Members

QByteArrayfromBase64(const QByteArray & base64)
QByteArrayfromHex(const QByteArray & hexEncoded)
QByteArrayfromPercentEncoding(const QByteArray & input, char percent = '%')
QByteArrayfromRawData(const char * data, int size)
QByteArraynumber(int n, int base = 10)
QByteArraynumber(uint n, int base = 10)
QByteArraynumber(qlonglong n, int base = 10)
QByteArraynumber(qulonglong n, int base = 10)
QByteArraynumber(double n, char f = 'g', int prec = 6)

Related Non-Members

quint16qChecksum(const char * data, uint len)
QByteArrayqCompress(const QByteArray & data, int compressionLevel = -1)
QByteArrayqCompress(const uchar * data, int nbytes, int compressionLevel = -1)
QByteArrayqUncompress(const QByteArray & data)
QByteArrayqUncompress(const uchar * data, int nbytes)
intqsnprintf(char * str, size_t n, const char * fmt, ...)
intqstrcmp(const char * str1, const char * str2)
char *qstrcpy(char * dst, const char * src)
char *qstrdup(const char * src)
intqstricmp(const char * str1, const char * str2)
uintqstrlen(const char * str)
intqstrncmp(const char * str1, const char * str2, uint len)
char *qstrncpy(char * dst, const char * src, uint len)
intqstrnicmp(const char * str1, const char * str2, uint len)
uintqstrnlen(const char * str, uint maxlen)
intqvsnprintf(char * str, size_t n, const char * fmt, va_list ap)
booloperator!=(const QByteArray & a1, const QByteArray & a2)
booloperator!=(const QByteArray & a1, const char * a2)
booloperator!=(const char * a1, const QByteArray & a2)
const QByteArrayoperator+(const QByteArray & a1, const QByteArray & a2)
const QByteArrayoperator+(const QByteArray & a1, const char * a2)
const QByteArrayoperator+(const QByteArray & a1, char a2)
const QByteArrayoperator+(const char * a1, const QByteArray & a2)
const QByteArrayoperator+(char a1, const QByteArray & a2)
booloperator<(const QByteArray & a1, const QByteArray & a2)
booloperator<(const QByteArray & a1, const char * a2)
booloperator<(const char * a1, const QByteArray & a2)
QDataStream &operator<<(QDataStream & out, const QByteArray & ba)
booloperator<=(const QByteArray & a1, const QByteArray & a2)
booloperator<=(const QByteArray & a1, const char * a2)
booloperator<=(const char * a1, const QByteArray & a2)
booloperator==(const QByteArray & a1, const QByteArray & a2)
booloperator==(const QByteArray & a1, const char * a2)
booloperator==(const char * a1, const QByteArray & a2)
booloperator>(const QByteArray & a1, const QByteArray & a2)
booloperator>(const QByteArray & a1, const char * a2)
booloperator>(const char * a1, const QByteArray & a2)
booloperator>=(const QByteArray & a1, const QByteArray & a2)
booloperator>=(const QByteArray & a1, const char * a2)
booloperator>=(const char * a1, const QByteArray & a2)
QDataStream &operator>>(QDataStream & in, QByteArray & ba)

Macros

Detailed Description

TheQByteArray class provides an array of bytes.

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

In addition toQByteArray, Qt also provides theQString class to store string data. For most purposes,QString is the class you want to use. It stores 16-bit Unicode characters, making it easy to store non-ASCII/non-Latin-1 characters in your application. Furthermore,QString is used throughout in the Qt API. The two main cases whereQByteArray 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 aQByteArray is simply to pass aconst char * to its constructor. For example, the following code creates a byte array of size 5 containing the data "Hello":

QByteArray ba("Hello");

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

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

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

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

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

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

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

To extract many bytes at a time, useleft(),right(), ormid().

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

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

To obtain a pointer to the actual character data, calldata() orconstData(). 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 theQByteArray. It is also guaranteed that the data ends with a '\0' byte unless theQByteArray was created from araw data. This '\0' byte is automatically provided byQByteArray and is not counted insize().

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

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

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

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

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

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

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

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

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

For historical reasons,QByteArray distinguishes between a null byte array and an empty byte array. Anull byte array is a byte array that is initialized usingQByteArray's default constructor or by passing (const char *)0 to the constructor. Anempty 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 trueQByteArray().isEmpty();// returns trueQByteArray("").isNull();// returns falseQByteArray("").isEmpty();// returns trueQByteArray("abc").isNull();// returns falseQByteArray("abc").isEmpty();// returns false

All functions exceptisNull() treat null byte arrays the same as empty byte arrays. For example,data() returns a pointer to a '\0' character for a null byte array (not a null pointer), andQByteArray() compares equal toQByteArray(""). We recommend that you always useisEmpty() and avoidisNull().

Notes on Locale

Number-String Conversions

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

8-bit Character Comparisons

InQByteArray, the notion of uppercase and lowercase and of which character is greater than or less than another character is locale dependent. This affects functions that support a case insensitive option or that compare or lowercase or uppercase their arguments. Case insensitive operations and comparisons will be accurate if both strings contain only ASCII characters. (If$LC_CTYPE is set, most Unix systems do "the right thing".) Functions that this affects includecontains(),indexOf(),lastIndexOf(), operator<(), operator<=(), operator>(), operator>=(),toLower() andtoUpper().

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

See alsoQString andQBitArray.

Member Function Documentation

QByteArray::QByteArray()

Constructs an empty byte array.

See alsoisEmpty().

QByteArray::QByteArray(constchar * str)

Constructs a byte array initialized with the stringstr.

QByteArray makes a deep copy of the string data.

QByteArray::QByteArray(constchar * data,int size)

Constructs a byte array containing the firstsize bytes of arraydata.

Ifdata is 0, a null byte array is constructed.

QByteArray makes a deep copy of the string data.

See alsofromRawData().

QByteArray::QByteArray(int size,char ch)

Constructs a byte array of sizesize with every byte set to characterch.

See alsofill().

QByteArray::QByteArray(constQByteArray & other)

Constructs a copy ofother.

This operation takesconstant time, becauseQByteArray isimplicitly shared. This makes returning aQByteArray from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), takinglinear time.

See alsooperator=().

QByteArray::~QByteArray()

Destroys the byte array.

QByteArray & QByteArray::append(constQByteArray & ba)

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

Example:

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

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

Note:QByteArray is animplicitly shared class. Consequently, ifthis is an emptyQByteArray, thenthis will just share the data held inba. In this case, no copying of data is done, takingconstant time. If a shared instance is modified, it will be copied (copy-on-write), takinglinear time.

Ifthis is not an emptyQByteArray, a deep copy of the data is performed, takinglinear time.

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

See alsooperator+=(),prepend(), andinsert().

QByteArray & QByteArray::append(constQString & str)

This is an overloaded function.

Appends the stringstr to this byte array. The Unicode data is converted into 8-bit characters usingQString::toAscii().

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

QByteArray & QByteArray::append(constchar * str)

This is an overloaded function.

Appends the stringstr to this byte array.

QByteArray & QByteArray::append(constchar * str,int len)

This function overloadsappend().

Appends the firstlen characters of the stringstr to this byte array and returns a reference to this byte array.

Iflen is negative, the length of the string will be determined automatically usingqstrlen(). Iflen is zero orstr is null, nothing is appended to the byte array. Ensure thatlen isnot longer thanstr.

QByteArray & QByteArray::append(char ch)

This is an overloaded function.

Appends the characterch to this byte array.

char QByteArray::at(int i) const

Returns the character at index positioni in the byte array.

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

See alsooperator[]().

int QByteArray::capacity() const

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

The sole purpose of this function is to provide a means of fine tuningQByteArray'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, callsize().

See alsoreserve() andsqueeze().

void QByteArray::chop(int n)

Removesn bytes from the end of the byte array.

Ifn is greater thansize(), the result is an empty byte array.

Example:

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

See alsotruncate(),resize(), andleft().

void QByteArray::clear()

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

See alsoresize() andisEmpty().

constchar * QByteArray::constData() const

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

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

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

See alsodata(),operator[](), andfromRawData().

bool QByteArray::contains(constQByteArray & ba) const

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

See alsoindexOf() andcount().

bool QByteArray::contains(constchar * str) const

This is an overloaded function.

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

bool QByteArray::contains(char ch) const

This is an overloaded function.

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

int QByteArray::count(constQByteArray & ba) const

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

See alsocontains() andindexOf().

int QByteArray::count(constchar * str) const

This is an overloaded function.

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

int QByteArray::count(char ch) const

This is an overloaded function.

Returns the number of occurrences of characterch in the byte array.

See alsocontains() andindexOf().

int QByteArray::count() const

This is an overloaded function.

Same assize().

char * QByteArray::data()

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

Example:

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

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

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

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

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

This one allocates the correct amount of space:

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

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

See alsoconstData() andoperator[]().

constchar * QByteArray::data() const

This is an overloaded function.

bool QByteArray::endsWith(constQByteArray & ba) const

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

Example:

QByteArray url("http://qt.nokia.com/index.html");if (url.endsWith(".html"))...

See alsostartsWith() andright().

bool QByteArray::endsWith(constchar * str) const

This is an overloaded function.

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

bool QByteArray::endsWith(char ch) const

This is an overloaded function.

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

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

Sets every byte in the byte array to characterch. Ifsize is different from -1 (the default), the byte array is resized to sizesize beforehand.

Example:

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

See alsoresize().

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

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

For example:

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

The algorithm used to decode Base64-encoded data is defined inRFC 2045.

See alsotoBase64().

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

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

For example:

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

See alsotoHex().

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

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

For example:

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

This function was introduced in Qt 4.4.

See alsotoPercentEncoding() andQUrl::fromPercentEncoding().

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

Constructs aQByteArray that uses the firstsize bytes of thedata array. The bytes arenot copied. TheQByteArray will contain thedata pointer. The caller guarantees thatdata will not be deleted or modified as long as thisQByteArray and any copies of it exist that have not been modified. In other words, becauseQByteArray is animplicitly shared class and the instance returned by this function contains thedata pointer, the caller must not deletedata or modify it directly as long as the returnedQByteArray and any copies exist. However,QByteArray does not take ownership ofdata, so theQByteArray destructor will never delete the rawdata, even when the lastQByteArray referring todata is destroyed.

A subsequent attempt to modify the contents of the returnedQByteArray or any copy made from it will cause it to create a deep copy of thedata array before doing the modification. This ensures that the rawdata array itself will never be modified byQByteArray.

Here is an example of how to read data using aQDataStream on raw data in memory without copying the raw data into aQByteArray:

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

Warning: A byte array created with fromRawData() isnot null-terminated, unless the raw data contains a 0 character at positionsize. While that does not matter forQDataStream or functions likeindexOf(), passing the byte array to a function accepting aconst char * expected to be '\0'-terminated will fail.

See alsosetRawData(),data(), andconstData().

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

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

Example:

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

See alsolastIndexOf(),contains(), andcount().

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

This is an overloaded function.

Returns the index position of the first occurrence of the stringstr in the byte array, searching forward from index positionfrom. Returns -1 ifstr could not be found.

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

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

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

This is an overloaded function.

Returns the index position of the first occurrence of the stringstr in the byte array, searching forward from index positionfrom. Returns -1 ifstr could not be found.

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

This is an overloaded function.

Returns the index position of the first occurrence of the characterch in the byte array, searching forward from index positionfrom. Returns -1 ifch could not be found.

Example:

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

See alsolastIndexOf() andcontains().

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

Inserts the byte arrayba at index positioni and returns a reference to this byte array.

Example:

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

See alsoappend(),prepend(),replace(), andremove().

QByteArray & QByteArray::insert(int i, constQString & str)

This is an overloaded function.

Inserts the stringstr at index positioni in the byte array. The Unicode data is converted into 8-bit characters usingQString::toAscii().

Ifi is greater thansize(), the array is first extended usingresize().

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

QByteArray & QByteArray::insert(int i, constchar * str)

This is an overloaded function.

Inserts the stringstr at positioni in the byte array.

Ifi is greater thansize(), the array is first extended usingresize().

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

This is an overloaded function.

Insertslen bytes of the stringstr at positioni in the byte array.

Ifi is greater thansize(), the array is first extended usingresize().

This function was introduced in Qt 4.6.

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

This is an overloaded function.

Inserts characterch at index positioni in the byte array. Ifi is greater thansize(), the array is first extended usingresize().

bool QByteArray::isEmpty() const

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

Example:

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

See alsosize().

bool QByteArray::isNull() const

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

Example:

QByteArray().isNull();// returns trueQByteArray("").isNull();// returns falseQByteArray("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 usingisEmpty().

See alsoisEmpty().

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

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

Example:

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

See alsoindexOf(),contains(), andcount().

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

This is an overloaded function.

Returns the index position of the last occurrence of the stringstr in the byte array, searching backward from index positionfrom. Iffrom is -1 (the default), the search starts at the last (size() - 1) byte. Returns -1 ifstr could not be found.

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

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

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

This is an overloaded function.

Returns the index position of the last occurrence of the stringstr in the byte array, searching backward from index positionfrom. Iffrom is -1 (the default), the search starts at the last (size() - 1) byte. Returns -1 ifstr could not be found.

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

This is an overloaded function.

Returns the index position of the last occurrence of characterch in the byte array, searching backward from index positionfrom. Iffrom is -1 (the default), the search starts at the last (size() - 1) byte. Returns -1 ifch could not be found.

Example:

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

See alsoindexOf() andcontains().

QByteArray QByteArray::left(int len) const

Returns a byte array that contains the leftmostlen bytes of this byte array.

The entire byte array is returned iflen is greater thansize().

Example:

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

See alsoright(),mid(),startsWith(), andtruncate().

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

Returns a byte array of sizewidth that contains this byte array padded by thefill character.

Iftruncate is false and thesize() of the byte array is more thanwidth, then the returned byte array is a copy of this byte array.

Iftruncate is true and thesize() of the byte array is more thanwidth, then any bytes in a copy of the byte array after positionwidth are removed, and the copy is returned.

Example:

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

See alsorightJustified().

int QByteArray::length() const

Same assize().

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

Returns a byte array containinglen bytes from this byte array, starting at positionpos.

Iflen is -1 (the default), orpos +len >=size(), returns a byte array containing all bytes starting at positionpos until the end of the byte array.

Example:

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

See alsoleft() andright().

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

Returns a byte array containing the string equivalent of the numbern to basebase (10 by default). Thebase can be any value between 2 and 36.

Example:

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

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

See alsosetNum() andtoInt().

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

This is an overloaded function.

See alsotoUInt().

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

This is an overloaded function.

See alsotoLongLong().

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

This is an overloaded function.

See alsotoULongLong().

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

This is an overloaded function.

Returns a byte array that contains the printed value ofn, formatted in formatf with precisionprec.

Argumentn is formatted according to thef format specified, which isg by default, and can be any of the following:

FormatMeaning
eformat as [-]9.9e[+|-]999
Eformat as [-]9.9E[+|-]999
fformat as [-]9.9
gusee orf format, whichever is the most concise
GuseE orf format, whichever is the most concise

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

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

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

See alsotoDouble().

QByteArray & QByteArray::prepend(constQByteArray & ba)

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

Example:

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

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

Note:QByteArray is animplicitly shared class. Consequently, ifthis is an emptyQByteArray, thenthis will just share the data held inba. In this case, no copying of data is done, takingconstant time. If a shared instance is modified, it will be copied (copy-on-write), takinglinear time.

Ifthis is not an emptyQByteArray, a deep copy of the data is performed, takinglinear time.

See alsoappend() andinsert().

QByteArray & QByteArray::prepend(constchar * str)

This is an overloaded function.

Prepends the stringstr to this byte array.

QByteArray & QByteArray::prepend(constchar * str,int len)

This is an overloaded function.

Prependslen bytes of the stringstr to this byte array.

This function was introduced in Qt 4.6.

QByteArray & QByteArray::prepend(char ch)

This is an overloaded function.

Prepends the characterch to this byte array.

void QByteArray::push_back(constQByteArray & other)

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

void QByteArray::push_back(constchar * str)

This is an overloaded function.

Same as append(str).

void QByteArray::push_back(char ch)

This is an overloaded function.

Same as append(ch).

void QByteArray::push_front(constQByteArray & other)

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

void QByteArray::push_front(constchar * str)

This is an overloaded function.

Same as prepend(str).

void QByteArray::push_front(char ch)

This is an overloaded function.

Same as prepend(ch).

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

Removeslen bytes from the array, starting at index positionpos, and returns a reference to the array.

Ifpos is out of range, nothing happens. Ifpos is valid, butpos +len is larger than the size of the array, the array is truncated at positionpos.

Example:

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

See alsoinsert() andreplace().

QByteArray QByteArray::repeated(int times) const

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

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

Example:

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

This function was introduced in Qt 4.5.

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

Replaceslen bytes from index positionpos with the byte arrayafter, and returns a reference to this byte array.

Example:

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

See alsoinsert() andremove().

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

This is an overloaded function.

Replaceslen bytes from index positionpos with the zero terminated stringafter.

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

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

This is an overloaded function.

Replaceslen bytes from index positionpos withalen bytes from the stringafter.after is allowed to have '\0' characters.

This function was introduced in Qt 4.7.

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

This is an overloaded function.

Replaces every occurrence of the byte arraybefore with the byte arrayafter.

Example:

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

QByteArray & QByteArray::replace(constchar * before, constQByteArray & after)

This is an overloaded function.

Replaces every occurrence of the stringbefore with the byte arrayafter.

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

This is an overloaded function.

Replaces every occurrence of the stringbefore with the stringafter. Since the sizes of the strings are given bybsize andasize, they may contain zero characters and do not need to be zero-terminated.

QByteArray & QByteArray::replace(constQByteArray & before, constchar * after)

This is an overloaded function.

Replaces every occurrence of the byte arraybefore with the stringafter.

QByteArray & QByteArray::replace(constQString & before, constQByteArray & after)

This is an overloaded function.

Replaces every occurrence of the stringbefore with the byte arrayafter. The Unicode data is converted into 8-bit characters usingQString::toAscii().

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

QByteArray & QByteArray::replace(constQString & before, constchar * after)

This is an overloaded function.

Replaces every occurrence of the stringbefore with the stringafter.

QByteArray & QByteArray::replace(constchar * before, constchar * after)

This is an overloaded function.

Replaces every occurrence of the stringbefore with the stringafter.

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

This is an overloaded function.

Replaces every occurrence of the characterbefore with the byte arrayafter.

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

This is an overloaded function.

Replaces every occurrence of the characterbefore with the stringafter. The Unicode data is converted into 8-bit characters usingQString::toAscii().

If theQString contains non-ASCII Unicode characters, using this function can lead to loss of information. You can disable this function by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

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

This is an overloaded function.

Replaces every occurrence of the characterbefore with the stringafter.

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

This is an overloaded function.

Replaces every occurrence of the characterbefore with the characterafter.

void QByteArray::reserve(int size)

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

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

See alsosqueeze() andcapacity().

void QByteArray::resize(int size)

Sets the size of the byte array tosize bytes.

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

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

See alsosize() andtruncate().

QByteArray QByteArray::right(int len) const

Returns a byte array that contains the rightmostlen bytes of this byte array.

The entire byte array is returned iflen is greater thansize().

Example:

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

See alsoendsWith(),left(), andmid().

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

Returns a byte array of sizewidth that contains thefill character followed by this byte array.

Iftruncate is false and the size of the byte array is more thanwidth, then the returned byte array is a copy of this byte array.

Iftruncate is true and the size of the byte array is more thanwidth, then the resulting byte array is truncated at positionwidth.

Example:

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

See alsoleftJustified().

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

Sets the byte array to the printed value ofn in basebase (10 by default) and returns a reference to the byte array. Thebase can be any value between 2 and 36.

Example:

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

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

See alsonumber() andtoInt().

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

This is an overloaded function.

See alsotoUInt().

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

This is an overloaded function.

See alsotoShort().

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

This is an overloaded function.

See alsotoUShort().

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

This is an overloaded function.

See alsotoLongLong().

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

This is an overloaded function.

See alsotoULongLong().

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

This is an overloaded function.

Sets the byte array to the printed value ofn, formatted in formatf with precisionprec, and returns a reference to the byte array.

The formatf can be any of the following:

FormatMeaning
eformat as [-]9.9e[+|-]999
Eformat as [-]9.9E[+|-]999
fformat as [-]9.9
gusee orf format, whichever is the most concise
GuseE orf format, whichever is the most concise

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

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

See alsotoDouble().

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

This is an overloaded function.

Sets the byte array to the printed value ofn, formatted in formatf with precisionprec, and returns a reference to the byte array.

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

See alsotoFloat().

QByteArray & QByteArray::setRawData(constchar * data,uint size)

Resets theQByteArray to use the firstsize bytes of thedata array. The bytes arenot copied. TheQByteArray will contain thedata pointer. The caller guarantees thatdata will not be deleted or modified as long as thisQByteArray and any copies of it exist that have not been modified.

This function can be used instead offromRawData() to re-use existingsQByteArray objects to save memory re-allocations.

This function was introduced in Qt 4.7.

See alsofromRawData(),data(), andconstData().

QByteArray QByteArray::simplified() const

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

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

Example:

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

See alsotrimmed().

int QByteArray::size() const

Returns the number of bytes in this byte array.

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

Example:

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

See alsoisEmpty() andresize().

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

Splits the byte array into subarrays whereversep occurs, and returns the list of those arrays. Ifsep 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 tuningQByteArray's memory usage. In general, you will rarely ever need to call this function.

See alsoreserve() andcapacity().

bool QByteArray::startsWith(constQByteArray & ba) const

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

Example:

QByteArray url("ftp://ftp.qt.nokia.com/");if (url.startsWith("ftp:"))...

See alsoendsWith() andleft().

bool QByteArray::startsWith(constchar * str) const

This is an overloaded function.

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

bool QByteArray::startsWith(char ch) const

This is an overloaded function.

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

void QByteArray::swap(QByteArray & other)

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

This function was introduced in Qt 4.8.

QByteArray QByteArray::toBase64() const

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

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

The algorithm used to encode Base64-encoded data is defined inRFC 2045.

See alsofromBase64().

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

Returns the byte array converted to adouble value.

Returns 0.0 if the conversion fails.

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

QByteArray string("1234.56");double a= string.toDouble();// a == 1234.56

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

See alsonumber().

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

Returns the byte array converted to afloat value.

Returns 0.0 if the conversion fails.

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

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

See alsonumber().

QByteArray QByteArray::toHex() const

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

See alsofromHex().

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

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

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

Returns 0 if the conversion fails.

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

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

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

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

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

This function was introduced in Qt 4.1.

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

See alsonumber().

QByteArray QByteArray::toLower() const

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

Example:

QByteArray x("Qt by NOKIA");QByteArray y= x.toLower();// y == "qt by nokia"

See alsotoUpper() and8-bit Character Comparisons.

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

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

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

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

To prevent characters from being encoded pass them toexclude. To force characters to be encoded pass them toinclude. Thepercent character is always encoded.

Example:

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

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

This function was introduced in Qt 4.4.

See alsofromPercentEncoding() andQUrl::toPercentEncoding().

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

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

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

Returns 0 if the conversion fails.

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

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

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

This function was introduced in Qt 4.1.

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

See alsonumber().

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

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

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

Returns 0 if the conversion fails.

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

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

See alsonumber().

QByteArray QByteArray::toUpper() const

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

Example:

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

See alsotoLower() and8-bit Character Comparisons.

QByteArray QByteArray::trimmed() const

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

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

Example:

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

Unlikesimplified(), trimmed() leaves internal whitespace alone.

See alsosimplified().

void QByteArray::truncate(int pos)

Truncates the byte array at index positionpos.

Ifpos is beyond the end of the array, nothing happens.

Example:

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

See alsochop(),resize(), andleft().

QByteArray::operator const char *() const

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

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

You can disable this operator by definingQT_NO_CAST_FROM_BYTEARRAY when you compile your applications.

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

See alsoconstData().

QByteArray::operator const void *() const

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

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

You can disable this operator by definingQT_NO_CAST_FROM_BYTEARRAY when you compile your applications.

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

See alsoconstData().

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

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

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

Example:

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

Note:QByteArray is animplicitly shared class. Consequently, ifthis is an emptyQByteArray, thenthis will just share the data held inba. In this case, no copying of data is done, takingconstant time. If a shared instance is modified, it will be copied (copy-on-write), takinglinear time.

Ifthis is not an emptyQByteArray, a deep copy of the data is performed, takinglinear time.

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

See alsoappend() andprepend().

QByteArray & QByteArray::operator+=(constQString & str)

This is an overloaded function.

Appends the stringstr onto the end of this byte array and returns a reference to this byte array. The Unicode data is converted into 8-bit characters usingQString::toAscii().

If theQString contains non-ASCII Unicode characters, using this operator can lead to loss of information. You can disable this operator by definingQT_NO_CAST_TO_ASCII when you compile your applications. You then need to callQString::toAscii() (orQString::toLatin1() orQString::toUtf8() orQString::toLocal8Bit()) explicitly if you want to convert the data toconst char *.

QByteArray & QByteArray::operator+=(constchar * str)

This is an overloaded function.

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

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

This is an overloaded function.

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

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

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

Assignsother to this byte array and returns a reference to this byte array.

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

QByteArray & QByteArray::operator=(constchar * str)

This is an overloaded function.

Assignsstr to this byte array.

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

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

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

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

The comparison is case sensitive.

You can disable this operator by definingQT_NO_CAST_FROM_ASCII when you compile your applications. You then need to callQString::fromAscii(),QString::fromLatin1(),QString::fromUtf8(), orQString::fromLocal8Bit() explicitly if you want to convert the byte array to aQString before doing the comparison.

QByteRef QByteArray::operator[](int i)

Returns the byte at index positioni as a modifiable reference.

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

Example:

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

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

See alsoat().

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

This is an overloaded function.

Same as at(i).

QByteRef QByteArray::operator[](uint i)

This is an overloaded function.

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

This is an overloaded function.

Related Non-Members

quint16qChecksum(constchar * data,uint len)

Returns the CRC-16 checksum of the firstlen bytes ofdata.

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

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

QByteArrayqCompress(constQByteArray & data,int compressionLevel = -1)

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

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

See alsoqUncompress().

QByteArrayqCompress(constuchar * data,int nbytes,int compressionLevel = -1)

This is an overloaded function.

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

QByteArrayqUncompress(constQByteArray & data)

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

Returns an emptyQByteArray if the input data was corrupt.

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

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

See alsoqCompress().

QByteArrayqUncompress(constuchar * data,int nbytes)

This is an overloaded function.

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

intqsnprintf(char * str,size_t n, constchar * fmt, ...)

A portable snprintf() function, calls qvsnprintf.

fmt is theprintf() format string. The result is put intostr, which is a buffer of at leastn bytes.

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

See alsoqvsnprintf() andQString::sprintf().

intqstrcmp(constchar * str1, constchar * str2)

A safestrcmp() function.

Comparesstr1 andstr2. Returns a negative value ifstr1 is less thanstr2, 0 ifstr1 is equal tostr2 or a positive value ifstr1 is greater thanstr2.

Special case 1: Returns 0 ifstr1 andstr2 are both 0.

Special case 2: Returns an arbitrary non-zero value ifstr1 is 0 orstr2 is 0 (but not both).

See alsoqstrncmp(),qstricmp(),qstrnicmp(), and8-bit Character Comparisons.

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

Copies all the characters up to and including the '\0' fromsrc intodst and returns a pointer todst. Ifsrc is 0, it immediately returns 0.

This function assumes thatdst is large enough to hold the contents ofsrc.

See alsoqstrncpy().

char *qstrdup(constchar * src)

Returns a duplicate string.

Allocates space for a copy ofsrc, copies it, and returns a pointer to the copy. Ifsrc is 0, it immediately returns 0.

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

intqstricmp(constchar * str1, constchar * str2)

A safestricmp() function.

Comparesstr1 andstr2 ignoring the case of the characters. The encoding of the strings is assumed to be Latin-1.

Returns a negative value ifstr1 is less thanstr2, 0 ifstr1 is equal tostr2 or a positive value ifstr1 is greater thanstr2.

Special case 1: Returns 0 ifstr1 andstr2 are both 0.

Special case 2: Returns a random non-zero value ifstr1 is 0 orstr2 is 0 (but not both).

See alsoqstrcmp(),qstrncmp(),qstrnicmp(), and8-bit Character Comparisons.

uintqstrlen(constchar * str)

A safestrlen() function.

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

See alsoqstrnlen().

intqstrncmp(constchar * str1, constchar * str2,uint len)

A safestrncmp() function.

Compares at mostlen bytes ofstr1 andstr2.

Returns a negative value ifstr1 is less thanstr2, 0 ifstr1 is equal tostr2 or a positive value ifstr1 is greater thanstr2.

Special case 1: Returns 0 ifstr1 andstr2 are both 0.

Special case 2: Returns a random non-zero value ifstr1 is 0 orstr2 is 0 (but not both).

See alsoqstrcmp(),qstricmp(),qstrnicmp(), and8-bit Character Comparisons.

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

A safestrncpy() function.

Copies at mostlen bytes fromsrc (stopping atlen or the terminating '\0' whichever comes first) intodst and returns a pointer todst. Guarantees thatdst is '\0'-terminated. Ifsrc ordst is 0, returns 0 immediately.

This function assumes thatdst is at leastlen characters long.

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

See alsoqstrcpy().

intqstrnicmp(constchar * str1, constchar * str2,uint len)

A safestrnicmp() function.

Compares at mostlen bytes ofstr1 andstr2 ignoring the case of the characters. The encoding of the strings is assumed to be Latin-1.

Returns a negative value ifstr1 is less thanstr2, 0 ifstr1 is equal tostr2 or a positive value ifstr1 is greater thanstr2.

Special case 1: Returns 0 ifstr1 andstr2 are both 0.

Special case 2: Returns a random non-zero value ifstr1 is 0 orstr2 is 0 (but not both).

See alsoqstrcmp(),qstrncmp(),qstricmp(), and8-bit Character Comparisons.

uintqstrnlen(constchar * str,uint maxlen)

A safestrnlen() function.

Returns the number of characters that precede the terminating '\0', but at mostmaxlen. Ifstr is 0, returns 0.

This function was introduced in Qt 4.2.

See alsoqstrlen().

intqvsnprintf(char * str,size_t n, constchar * fmt,va_list ap)

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

fmt is theprintf() format string. The result is put intostr, which is a buffer of at leastn bytes.

The caller is responsible to callva_end() onap.

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

Ideally, you should never call this function but useQString::sprintf() instead.

See alsoqsnprintf() andQString::sprintf().

booloperator!=(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is not equal to byte arraya2; otherwise returns false.

booloperator!=(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is not equal to stringa2; otherwise returns false.

booloperator!=(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is not equal to byte arraya2; otherwise returns false.

constQByteArrayoperator+(constQByteArray & a1, constQByteArray & a2)

Returns a byte array that is the result of concatenating byte arraya1 and byte arraya2.

See alsoQByteArray::operator+=().

constQByteArrayoperator+(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating byte arraya1 and stringa2.

constQByteArrayoperator+(constQByteArray & a1,char a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating byte arraya1 and charactera2.

constQByteArrayoperator+(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating stringa1 and byte arraya2.

constQByteArrayoperator+(char a1, constQByteArray & a2)

This is an overloaded function.

Returns a byte array that is the result of concatenating charactera1 and byte arraya2.

booloperator<(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically less than byte arraya2; otherwise returns false.

booloperator<(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically less than stringa2; otherwise returns false.

booloperator<(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is lexically less than byte arraya2; otherwise returns false.

QDataStream &operator<<(QDataStream & out, constQByteArray & ba)

Writes byte arrayba to the streamout and returns a reference to the stream.

See alsoSerializing Qt Data Types.

booloperator<=(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically less than or equal to byte arraya2; otherwise returns false.

booloperator<=(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically less than or equal to stringa2; otherwise returns false.

booloperator<=(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is lexically less than or equal to byte arraya2; otherwise returns false.

booloperator==(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is equal to byte arraya2; otherwise returns false.

booloperator==(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is equal to stringa2; otherwise returns false.

booloperator==(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is equal to byte arraya2; otherwise returns false.

booloperator>(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically greater than byte arraya2; otherwise returns false.

booloperator>(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically greater than stringa2; otherwise returns false.

booloperator>(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is lexically greater than byte arraya2; otherwise returns false.

booloperator>=(constQByteArray & a1, constQByteArray & a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically greater than or equal to byte arraya2; otherwise returns false.

booloperator>=(constQByteArray & a1, constchar * a2)

This is an overloaded function.

Returns true if byte arraya1 is lexically greater than or equal to stringa2; otherwise returns false.

booloperator>=(constchar * a1, constQByteArray & a2)

This is an overloaded function.

Returns true if stringa1 is lexically greater than or equal to byte arraya2; otherwise returns false.

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

Reads a byte array intoba from the streamin and returns a reference to the stream.

See alsoSerializing Qt Data Types.

Macro Documentation

QT_NO_CAST_FROM_BYTEARRAY

Disables automatic conversions fromQByteArray to const char * or const void *.

See alsoQT_NO_CAST_TO_ASCII andQT_NO_CAST_FROM_ASCII.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp