1
/****************************************************************************
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
5
** This file is part of the core module of the Qt Toolkit.
7
** This file may be distributed under the terms of the Q Public License
8
** as defined by Trolltech AS of Norway and appearing in the file
9
** LICENSE.QPL included in the packaging of this file.
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 as published by the Free Software
13
** Foundation and appearing in the file LICENSE.GPL included in the
14
** packaging of this file.
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
17
** information about Qt Commercial License Agreements.
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
21
** Contact info@trolltech.com if any conditions of this licensing are
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27
****************************************************************************/
29
#include "qbytearray.h"
30
#include "qbytearraymatcher.h"
35
#include "qlocale_p.h"
36
#include "qunicodetables_p.h"
37
#ifndef QT_NO_DATASTREAM
38
#include <qdatastream.h>
41
#ifndef QT_NO_COMPRESS
48
int qAllocMore(int alloc, int extra)
50
const int page = 1<<12;
54
nalloc = (1<<3) + ((alloc >>3) << 3);
55
} else if (alloc < page) {
57
while (nalloc < alloc)
60
nalloc = ((alloc + page) / page) * page;
62
return nalloc - extra;
65
/*****************************************************************************
66
Safe and portable C string functions; extensions to standard string.h
67
*****************************************************************************/
69
/*! \relates QByteArray
71
Returns a duplicate string.
73
Allocates space for a copy of \a src, copies it, and returns a
74
pointer to the copy. If \a src is 0, it immediately returns 0.
76
Ownership is passed to the caller, so the returned string must be
77
deleted using \c delete[].
80
char *qstrdup(const char *src)
84
char *dst = new char[strlen(src) + 1];
85
return qstrcpy(dst, src);
88
/*! \relates QByteArray
90
Copies all the characters up to and including the '\\0' from \a
91
src into \a dst and returns a pointer to \a dst. If \a src is 0,
92
it immediately returns 0.
94
This function assumes that \a dst is large enough to hold the
100
char *qstrcpy(char *dst, const char *src)
104
#if defined(_MSC_VER) && _MSC_VER >= 1400
105
int len = qstrlen(src);
106
// This is actually not secure!!! It will be fixed
107
// properly in a later release!
108
if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
112
return strcpy(dst, src);
116
/*! \relates QByteArray
118
A safe strncpy() function.
120
Copies at most \a len bytes from \a src (stopping at \a len or the
121
terminating '\\0' whichever comes first) into \a dst and returns a
122
pointer to \a dst. Guarantees that \a dst is '\\0'-terminated. If
123
\a src or \a dst is 0, returns 0 immediately.
125
This function assumes that \a dst is at least \a len characters
131
char *qstrncpy(char *dst, const char *src, uint len)
135
#if defined(_MSC_VER) && _MSC_VER >= 1400
136
strncpy_s(dst, len, src, len-1);
138
strncpy(dst, src, len);
145
/*! \fn uint qstrlen(const char *str);
149
A safe strlen() function.
151
Returns the number of characters that precede the terminating '\\0',
155
/*! \relates QByteArray
157
A safe strcmp() function.
159
Compares \a str1 and \a str2. Returns a negative value if \a str1
160
is less than \a str2, 0 if \a str1 is equal to \a str2 or a
161
positive value if \a str1 is greater than \a str2.
163
Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
165
Special case 2: Returns a random non-zero value if \a str1 is 0
166
or \a str2 is 0 (but not both).
168
\sa qstrncmp(), qstricmp(), qstrnicmp(),
169
{Note on 8-bit character comparisons}
171
int qstrcmp(const char *str1, const char *str2)
173
return (str1 && str2) ? strcmp(str1, str2)
174
: (str1 ? 1 : (str2 ? -1 : 0));
177
/*! \fn int qstrncmp(const char *str1, const char *str2, uint len);
181
A safe strncmp() function.
183
Compares at most \a len bytes of \a str1 and \a str2.
185
Returns a negative value if \a str1 is less than \a str2, 0 if \a
186
str1 is equal to \a str2 or a positive value if \a str1 is greater
189
Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
191
Special case 2: Returns a random non-zero value if \a str1 is 0
192
or \a str2 is 0 (but not both).
194
\sa qstrcmp(), qstricmp(), qstrnicmp(),
195
{Note on 8-bit character comparisons}
198
/*! \relates QByteArray
200
A safe stricmp() function.
202
Compares \a str1 and \a str2 ignoring the case of the
203
characters. The encoding of the strings is assumed to be Latin-1.
205
Returns a negative value if \a str1 is less than \a str2, 0 if \a
206
str1 is equal to \a str2 or a positive value if \a str1 is greater
209
Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
211
Special case 2: Returns a random non-zero value if \a str1 is 0
212
or \a str2 is 0 (but not both).
214
\sa qstrcmp(), qstrncmp(), qstrnicmp(),
215
{Note on 8-bit character comparisons}
218
int qstricmp(const char *str1, const char *str2)
220
register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
221
register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
225
return s1 ? 1 : (s2 ? -1 : 0);
226
for (; !(res = (c = QUnicodeTables::lower(*s1)) - QUnicodeTables::lower(*s2)); s1++, s2++)
227
if (!c) // strings are equal
232
/*! \relates QByteArray
234
A safe strnicmp() function.
236
Compares at most \a len bytes of \a str1 and \a str2 ignoring the
237
case of the characters. The encoding of the strings is assumed to
240
Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
241
is equal to \a str2 or a positive value if \a str1 is greater than \a
244
Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
246
Special case 2: Returns a random non-zero value if \a str1 is 0
247
or \a str2 is 0 (but not both).
249
\sa qstrcmp(), qstrncmp(), qstricmp(),
250
{Note on 8-bit character comparisons}
253
int qstrnicmp(const char *str1, const char *str2, uint len)
255
register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
256
register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
260
return s1 ? 1 : (s2 ? -1 : 0);
261
for (; len--; s1++, s2++) {
262
if ((res = (c = QUnicodeTables::lower(*s1)) - QUnicodeTables::lower(*s2)))
264
if (!c) // strings are equal
270
// the CRC table below is created by the following piece of code
272
static void createCRC16Table() // build CRC16 lookup table
274
register unsigned int i;
275
register unsigned int j;
276
unsigned short crc_tbl[16];
277
unsigned int v0, v1, v2, v3;
278
for (i = 0; i < 16; i++) {
285
#define SET_BIT(x, b, v) (x) |= (v) << (b)
300
printf("static const quint16 crc_tbl[16] = {\n");
301
for (int i = 0; i < 16; i +=4)
302
printf(" 0x%04x, 0x%04x, 0x%04x, 0x%04x,\n", crc_tbl[i], crc_tbl[i+1], crc_tbl[i+2], crc_tbl[i+3]);
307
static const quint16 crc_tbl[16] = {
308
0x0000, 0x1081, 0x2102, 0x3183,
309
0x4204, 0x5285, 0x6306, 0x7387,
310
0x8408, 0x9489, 0xa50a, 0xb58b,
311
0xc60c, 0xd68d, 0xe70e, 0xf78f
314
/*! \relates QByteArray
316
Returns the CRC-16 checksum of the first \a len bytes of \a data.
318
The checksum is independent of the byte order (endianness).
321
quint16 qChecksum(const char *data, uint len)
323
register quint16 crc = 0xffff;
325
const uchar *p = reinterpret_cast<const uchar *>(data);
328
crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
330
crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
332
return ~crc & 0xffff;
335
/*! \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
339
Compresses the \a data byte array and returns the compressed data
342
The \a compressionLevel parameter specifies how much compression
343
should be used. Valid values are between 0 and 9, with 9
344
corresponding to the greatest compression (i.e. smaller compressed
345
data) at the cost of using a slower algorithm. Smaller values (8,
346
7, ..., 1) provide successively less compression at slightly
347
faster speeds. The value 0 corresponds to no compression at all.
348
The default value is -1, which specifies zlib's default
354
/*! \relates QByteArray
358
Compresses the first \a nbytes of \a data and returns the
359
compressed data in a new byte array.
362
#ifndef QT_NO_COMPRESS
363
QByteArray qCompress(const uchar* data, int nbytes, int compressionLevel)
366
return QByteArray(4, '\0');
369
qWarning("qCompress: Data is null");
372
if (compressionLevel < -1 || compressionLevel > 9)
373
compressionLevel = -1;
375
ulong len = nbytes + nbytes / 100 + 13;
379
bazip.resize(len + 4);
380
res = ::compress2((uchar*)bazip.data()+4, &len, (uchar*)data, nbytes, compressionLevel);
384
bazip.resize(len + 4);
385
bazip[0] = (nbytes & 0xff000000) >> 24;
386
bazip[1] = (nbytes & 0x00ff0000) >> 16;
387
bazip[2] = (nbytes & 0x0000ff00) >> 8;
388
bazip[3] = (nbytes & 0x000000ff);
391
qWarning("qCompress: Z_MEM_ERROR: Not enough memory");
398
} while (res == Z_BUF_ERROR);
404
/*! \fn QByteArray qUncompress(const QByteArray& data)
408
Uncompresses the \a data byte array and returns a new byte array
409
with the uncompressed data.
411
Returns an empty QByteArray if the input data was corrupt.
413
This function will uncompress data compressed with qCompress()
414
from this and any earlier Qt version, back to Qt 3.1 when this
420
/*! \relates QByteArray
424
Uncompresses the first \a nbytes of \a data and returns a new byte
425
array with the uncompressed data.
428
#ifndef QT_NO_COMPRESS
429
QByteArray qUncompress(const uchar* data, int nbytes)
432
qWarning("qUncompress: Data is null");
436
if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
437
qWarning("qUncompress: Input data is corrupted");
440
ulong expectedSize = (data[0] << 24) | (data[1] << 16) |
441
(data[2] << 8) | (data[3] );
442
ulong len = qMax(expectedSize, 1ul);
447
res = ::uncompress((uchar*)baunzip.data(), &len,
448
(uchar*)data+4, nbytes-4);
452
if ((int)len != baunzip.size())
456
qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
462
qWarning("qUncompress: Z_DATA_ERROR: Input data is corrupted");
465
} while (res == Z_BUF_ERROR);
468
baunzip = QByteArray();
474
static inline bool qIsUpper(char c)
476
return c >= 'A' && c <= 'Z';
479
static inline char qToLower(char c)
481
if (c >= 'A' && c <= 'Z')
482
return c - 'A' + 'a';
487
Q_CORE_EXPORT QByteArray::Data QByteArray::shared_null = {Q_ATOMIC_INIT(1), 0, 0, shared_null.array, {0} };
488
QByteArray::Data QByteArray::shared_empty = { Q_ATOMIC_INIT(1), 0, 0, shared_empty.array, {0} };
492
\brief The QByteArray class provides an array of bytes.
500
QByteArray can be used to store both raw bytes (including '\\0's)
501
and traditional 8-bit '\\0'-terminated strings. Using QByteArray
502
is much more convenient than using \c{const char *}. Behind the
503
scenes, it always ensures that the data is followed by a '\\0'
504
terminator, and uses \l{implicit sharing} (copy-on-write) to
505
reduce memory usage and avoid needless copying of data.
507
In addition to QByteArray, Qt also provides the QString class to
508
store string data. For most purposes, QString is the class you
509
want to use. It stores 16-bit Unicode characters, making it easy
510
to store non-ASCII/non-Latin-1 characters in your application.
511
Furthermore, QString is used throughout in the Qt API. The two
512
main cases where QByteArray is appropriate are when you need to
513
store raw binary data, and when memory conservation is critical
514
(e.g. with Qt/Embedded).
516
One way to initialize a QByteArray is simply to pass a \c{const
517
char *} to its constructor. For example, the following code
518
creates a byte array of size 5 containing the data "Hello":
521
QByteArray ba("Hello");
524
Although the size() is 5, the byte array also maintains an extra
525
'\\0' character at the end so that if a function is used that
526
asks for a pointer to the underlying data (e.g. a call to
527
data()), the data pointed to is guaranteed to be
530
QByteArray makes a deep copy of the \c{const char *} data, so you
531
can modify it later without experiencing side effects. (If for
532
performance reasons you don't want to take a deep copy of the
533
character data, use QByteArray::fromRawData() instead.)
535
Another approach is to set the size of the array using resize()
536
and to initialize the data byte per byte. QByteArray uses 0-based
537
indexes, just like C++ arrays. To access the byte at a particular
538
index position, you can use operator[](). On non-const byte
539
arrays, operator[]() returns a reference to a byte that can be
540
used on the left side of an assignment. For example:
552
For read-only access, an alternative syntax is to use at():
555
for (int i = 0; i < ba.size(); ++i) {
556
if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
557
cout << "Found character in range [a-f]" << endl;
561
at() can be faster than operator[](), because it never causes a
562
\l{deep copy} to occur.
564
To extract many bytes at a time, use left(), right(), or mid().
566
A QByteArray can embed '\\0' bytes. The size() function always
567
returns the size of the whole array, including embedded '\\0'
568
bytes. If you want to obtain the length of the data up to and
569
excluding the first '\\0' character, call qstrlen() on the byte
572
After a call to resize(), newly allocated bytes have undefined
573
values. To set all the bytes to a particular value, call fill().
575
To obtain a pointer to the actual character data, call data() or
576
constData(). These functions return a pointer to the beginning of
577
the data. The pointer is guaranteed to remain valid until a
578
non-const function is called on the QByteArray. It is also
579
guaranteed that the data ends with a '\\0' byte. This '\\0' byte
580
is automatically provided by QByteArray and is not counted in
583
QByteArray provides the following basic functions for modifying
584
the byte data: append(), prepend(), insert(), replace(), and
585
remove(). For example:
589
x.prepend("rock "); // x == "rock and"
590
x.append(" roll"); // x == "rock and roll"
591
x.replace(5, 3, "&"); // x == "rock & roll"
594
The replace() and remove() functions' first two arguments are the
595
position from which to start erasing and the number of bytes that
598
If you are building a QByteArray gradually and know in advance
599
approximately how many bytes the QByteArray will contain,
600
you can call reserve(), asking QByteArray to preallocate a
601
certain amount of memory. You can also call capacity() to find
602
out how much memory QByteArray actually allocated.
604
A frequent requirement is to remove whitespace characters from a
605
byte array ('\\n', '\\t', ' ', etc.). If you want to remove
606
whitespace from both ends of a QByteArray, use trimmed(). If you
607
want to remove whitespace from both ends and replace multiple
608
consecutive whitespaces with a single space character within the
609
byte array, use simplified().
611
If you want to find all occurrences of a particular character or
612
substring in a QByteArray, use indexOf() or lastIndexOf(). The
613
former searches forward starting from a given index position, the
614
latter searches backward. Both return the index position of the
615
character or substring if they find it; otherwise, they return -1.
616
For example, here's a typical loop that finds all occurrences of a
617
particular substring:
620
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
622
while ((j = ba.indexOf("<b>", j)) != -1) {
623
cout << "Found <b> tag at index position " << j << endl;
628
If you simply want to check whether a QByteArray contains a
629
particular character or substring, use contains(). If you want to
630
find out how many times a particular character or substring
631
occurs in the byte array, use count(). If you want to replace all
632
occurrences of a particular value with another, use one of the
633
two-parameter replace() overloads.
635
QByteArrays can be compared using overloaded operators such as
636
operator<(), operator<=(), operator==(), operator>=(), and so on.
637
The comparison is based exclusively on the numeric values
638
of the characters and is very fast, but is not what a human would
639
expect. QString::localeAwareCompare() is a better choice for
640
sorting user-interface strings.
642
For historical reasons, QByteArray distinguishes between a null
643
byte array and an empty byte array. A \e null byte array is a
644
byte array that is initialized using QByteArray's default
645
constructor or by passing (const char *)0 to the constructor. An
646
\e empty byte array is any byte array with size 0. A null byte
647
array is always empty, but an empty byte array isn't necessarily
651
QByteArray().isNull(); // returns true
652
QByteArray().isEmpty(); // returns true
654
QByteArray("").isNull(); // returns false
655
QByteArray("").isEmpty(); // returns true
657
QByteArray("abc").isNull(); // returns false
658
QByteArray("abc").isEmpty(); // returns false
661
All functions except isNull() treat null byte arrays the same as
662
empty byte arrays. For example, data() returns a pointer to a
663
'\\0' character for a null byte array (\e not a null pointer),
664
and QByteArray() compares equal to QByteArray(""). We recommend
665
that you always use isEmpty() and avoid isNull().
667
\section1 Note on 8-bit Character Comparisons
669
In QByteArray, the notion of uppercase and lowercase and of which
670
character is greater than or less than another character is
671
locale dependent. This affects functions that support a case
672
insensitive option or that compare or lowercase or uppercase
673
their arguments. Case insensitive operations and comparisons will
674
be accurate if both strings contain only ASCII characters. (If \c
675
$LC_CTYPE is set, most Unix systems do "the right thing".)
676
Functions that this affects include contains(), indexOf(),
677
lastIndexOf(), operator<(), operator<=(), operator>(),
678
operator>=(), toLower() and toUpper().
680
This issue does not apply to QStrings since they represent
681
characters using Unicode.
683
\sa QString, QBitArray
686
/*! \fn QByteArray::iterator QByteArray::begin()
691
/*! \fn QByteArray::const_iterator QByteArray::begin() const
696
/*! \fn QByteArray::const_iterator QByteArray::constBegin() const
701
/*! \fn QByteArray::iterator QByteArray::end()
706
/*! \fn QByteArray::const_iterator QByteArray::end() const
711
/*! \fn QByteArray::const_iterator QByteArray::constEnd() const
716
/*! \fn void QByteArray::push_back(const QByteArray &other)
718
This function is provided for STL compatibility. It is equivalent
722
/*! \fn void QByteArray::push_back(const char *str)
726
Same as append(\a str).
729
/*! \fn void QByteArray::push_back(char ch)
733
Same as append(\a ch).
736
/*! \fn void QByteArray::push_front(const QByteArray &other)
738
This function is provided for STL compatibility. It is equivalent
739
to prepend(\a other).
742
/*! \fn void QByteArray::push_front(const char *str)
746
Same as prepend(\a str).
749
/*! \fn void QByteArray::push_front(char ch)
753
Same as prepend(\a ch).
756
/*! \fn QByteArray::QByteArray(const QByteArray &other)
758
Constructs a copy of \a other.
760
This operation takes \l{constant time}, because QByteArray is
761
\l{implicitly shared}. This makes returning a QByteArray from a
762
function very fast. If a shared instance is modified, it will be
763
copied (copy-on-write), and that takes \l{linear time}.
768
/*! \fn QByteArray::~QByteArray()
769
Destroys the byte array.
773
Assigns \a other to this byte array and returns a reference to
776
QByteArray &QByteArray::operator=(const QByteArray & other)
780
x = qAtomicSetPtr(&d, x);
790
Assigns \a str to this byte array.
793
QByteArray &QByteArray::operator=(const char *str)
801
int len = qstrlen(str);
802
if (d->ref != 1 || len > d->alloc || (len < d->size && len < d->alloc >> 1))
805
memcpy(x->data, str, len + 1); // include null terminator
809
x = qAtomicSetPtr(&d, x);
815
/*! \fn int QByteArray::size() const
817
Returns the number of bytes in this byte array.
819
The last byte in the byte array is at position size() - 1. In
820
addition, QByteArray ensures that the byte at position size() is
821
always '\\0', so that you can use the return value of data() and
822
constData() as arguments to functions that expect
823
'\\0'-terminated strings.
827
QByteArray ba("Hello");
828
int n = ba.size(); // n == 5
829
ba.data()[0]; // returns 'H'
830
ba.data()[4]; // returns 'o'
831
ba.data()[5]; // returns '\0'
834
\sa isEmpty(), resize()
837
/*! \fn bool QByteArray::isEmpty() const
839
Returns true if the byte array has size 0; otherwise returns false.
843
QByteArray().isEmpty(); // returns true
844
QByteArray("").isEmpty(); // returns true
845
QByteArray("abc").isEmpty(); // returns false
851
/*! \fn int QByteArray::capacity() const
853
Returns the maximum number of bytes that can be stored in the
854
byte array without forcing a reallocation.
856
The sole purpose of this function is to provide a means of fine
857
tuning QByteArray's memory usage. In general, you will rarely
858
ever need to call this function. If you want to know how many
859
bytes are in the byte array, call size().
861
\sa reserve(), squeeze()
864
/*! \fn void QByteArray::reserve(int size)
866
Attempts to allocate memory for at least \a size bytes. If you
867
know in advance how large the byte array will be, you can call
868
this function, and if you call resize() often you are likely to
869
get better performance. If \a size is an underestimate, the worst
870
that will happen is that the QByteArray will be a bit slower.
872
The sole purpose of this function is to provide a means of fine
873
tuning QByteArray's memory usage. In general, you will rarely
874
ever need to call this function. If you want to change the size
875
of the byte array, call resize().
877
\sa squeeze(), capacity()
880
/*! \fn void QByteArray::squeeze()
882
Releases any memory not required to store the array's data.
884
The sole purpose of this function is to provide a means of fine
885
tuning QByteArray's memory usage. In general, you will rarely
886
ever need to call this function.
888
\sa reserve(), capacity()
891
/*! \fn QByteArray::operator const char *() const
893
Returns a pointer to the data stored in the byte array. The
894
pointer can be used to access the bytes that compose the array.
895
The data is '\\0'-terminated. The pointer remains valid as long
896
as the array isn't reallocated.
898
This operator is mostly useful to pass a byte array to a function
899
that accepts a \c{const char *}.
901
Note: A QByteArray can store any byte values including '\\0's,
902
but most functions that take \c{char *} arguments assume that the
903
data ends at the first '\\0' they encounter.
908
/*! \fn QByteArray::operator const void *() const
910
Returns a void pointer to the data.
912
This operator is mostly useful to pass a byte array to a function
913
that accepts a void *.
918
/*! \fn char *QByteArray::data()
920
Returns a pointer to the data stored in the byte array. The
921
pointer can be used to access and modify the bytes that compose
922
the array. The data is '\\0'-terminated.
926
QByteArray ba("Hello world");
927
char *data = ba.data();
929
cout << "[" << *data << "]" << endl;
934
The pointer remains valid as long as the byte array isn't
937
This function is mostly useful to pass a byte array to a function
938
that accepts a \c{const char *}.
940
Note: A QByteArray can store any byte values including '\\0's,
941
but most functions that take \c{char *} arguments assume that the
942
data ends at the first '\\0' they encounter.
944
\sa constData(), operator[]()
947
/*! \fn const char *QByteArray::data() const
952
/*! \fn const char *QByteArray::constData() const
954
Returns a pointer to the data stored in the byte array. The
955
pointer can be used to access the bytes that compose the array.
956
The data is '\\0'-terminated. The pointer remains valid as long
957
as the byte array isn't reallocated.
959
This function is mostly useful to pass a byte array to a function
960
that accepts a \c{const char *}.
962
Note: A QByteArray can store any byte values including '\\0's,
963
but most functions that take \c{char *} arguments assume that the
964
data ends at the first '\\0' they encounter.
966
\sa data(), operator[]()
969
/*! \fn void QByteArray::detach()
974
/*! \fn bool QByteArray::isDetached() const
979
/*! \fn char QByteArray::at(int i) const
981
Returns the character at index position \a i in the byte array.
983
\a i must be a valid index position in the byte array (i.e., 0 <=
989
/*! \fn QByteRef QByteArray::operator[](int i)
991
Returns the byte at index position \a i as a modifiable reference.
993
If an assignment is made beyond the end of the byte array, the
994
array is extended with resize() before the assignment takes
1000
for (int i = 0; i < 10; ++i)
1002
// ba == "ABCDEFGHIJ"
1005
The return value is of type QByteRef, a helper class for
1006
QByteArray. When you get an object of type QByteRef, you can use
1007
it as if it were a char &. If you assign to it, the assignment
1008
will apply to the character in the QByteArray from which you got
1014
/*! \fn char QByteArray::operator[](int i) const
1021
/*! \fn QByteRef QByteArray::operator[](uint i)
1026
/*! \fn char QByteArray::operator[](uint i) const
1031
/*! \fn QBool QByteArray::contains(const QByteArray &ba) const
1033
Returns true if the byte array contains an occurrence of the byte
1034
array \a ba; otherwise returns false.
1036
\sa indexOf(), count()
1039
/*! \fn QBool QByteArray::contains(const char *str) const
1043
Returns true if the byte array contains the string \a str;
1044
otherwise returns false.
1047
/*! \fn QBool QByteArray::contains(char ch) const
1051
Returns true if the byte array contains the character \a ch;
1052
otherwise returns false.
1057
Truncates the byte array at index position \a pos.
1059
If \a pos is beyond the end of the array, nothing happens.
1063
QByteArray ba("Stockholm");
1064
ba.truncate(5); // ba == "Stock"
1067
\sa chop(), resize(), left()
1069
void QByteArray::truncate(int pos)
1077
Removes \a n bytes from the end of the byte array.
1079
If \a n is greater than size(), the result is an empty byte
1084
QByteArray ba("STARTTLS\r\n");
1085
ba.chop(2); // ba == "STARTTLS"
1088
\sa truncate(), resize(), left()
1091
void QByteArray::chop(int n)
1094
resize(d->size - n);
1098
/*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1100
Appends the byte array \a ba onto the end of this byte array and
1101
returns a reference to this byte array.
1105
QByteArray x("free");
1106
QByteArray y("dom");
1111
This operation is typically very fast (\l{constant time}),
1112
because QByteArray preallocates extra space at the end of the
1113
character data so it can grow without reallocating the entire
1116
\sa append(), prepend()
1119
/*! \fn QByteArray &QByteArray::operator+=(const QString &str)
1123
Appends the string \a str onto the end of this byte array and
1124
returns a reference to this byte array. The Unicode data is
1125
converted into 8-bit characters using QString::toAscii().
1127
If the QString contains non-ASCII Unicode characters, using this
1128
operator can lead to loss of information. You can disable this
1129
operator by defining \c QT_NO_CAST_TO_ASCII when you compile your
1130
applications. You then need to call QString::toAscii() (or
1131
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1132
explicitly if you want to convert the data to \c{const char *}.
1135
/*! \fn QByteArray &QByteArray::operator+=(const char *str)
1139
Appends the string \a str onto the end of this byte array and
1140
returns a reference to this byte array.
1143
/*! \fn QByteArray &QByteArray::operator+=(char ch)
1147
Appends the character \a ch onto the end of this byte array and
1148
returns a reference to this byte array.
1151
/*! \fn int QByteArray::length() const
1156
/*! \fn bool QByteArray::isNull() const
1158
Returns true if this byte array is null; otherwise returns false.
1162
QByteArray().isNull(); // returns true
1163
QByteArray("").isNull(); // returns false
1164
QByteArray("abc").isNull(); // returns false
1167
Qt makes a distinction between null byte arrays and empty byte
1168
arrays for historical reasons. For most applications, what
1169
matters is whether or not a byte array contains any data,
1170
and this can be determined using isEmpty().
1175
/*! \fn QByteArray::QByteArray()
1177
Constructs an empty byte array.
1182
/*! \fn QByteArray::QByteArray(const char *str)
1184
Constructs a byte array initialized with the string \a str.
1186
QByteArray makes a deep copy of the string data.
1189
QByteArray::QByteArray(const char *str)
1196
int len = qstrlen(str);
1197
d = static_cast<Data *>(qMalloc(sizeof(Data)+len));
1202
d->alloc = d->size = len;
1204
memcpy(d->array, str, len+1); // include null terminator
1211
Constructs a byte array containing the first \a size bytes of
1214
If \a data is 0, a null byte array is constructed.
1216
QByteArray makes a deep copy of the string data.
1221
QByteArray::QByteArray(const char *data, int size)
1225
} else if (size <= 0) {
1228
d = static_cast<Data *>(qMalloc(sizeof(Data) + size));
1233
d->alloc = d->size = size;
1235
memcpy(d->array, data, size);
1236
d->array[size] = '\0';
1243
Constructs a byte array of size \a size with every byte set to
1249
QByteArray::QByteArray(int size, char ch)
1254
d = static_cast<Data *>(qMalloc(sizeof(Data)+size));
1259
d->alloc = d->size = size;
1261
d->array[size] = '\0';
1262
memset(d->array, ch, size);
1269
Sets the size of the byte array to \a size bytes.
1271
If \a size is greater than the current size, the byte array is
1272
extended to make it \a size bytes with the extra bytes added to
1273
the end. The new bytes are uninitialized.
1275
If \a size is less than the current size, bytes are removed from
1281
void QByteArray::resize(int size)
1284
Data *x = &shared_empty;
1286
x = qAtomicSetPtr(&d, x);
1287
if (!x->ref.deref())
1290
if (d->ref != 1 || size > d->alloc || (size < d->size && size < d->alloc >> 1))
1291
realloc(qAllocMore(size, sizeof(Data)));
1292
if (d->alloc >= size) {
1295
d->array[size] = '\0';
1301
Sets every byte in the byte array to character \a ch. If \a size
1302
is different from -1 (the default), the byte array is resized to
1303
size \a size beforehand.
1307
QByteArray ba("Istambul");
1318
QByteArray &QByteArray::fill(char ch, int size)
1320
resize(size < 0 ? d->size : size);
1322
memset(d->data, ch, d->size);
1326
void QByteArray::realloc(int alloc)
1328
if (d->ref != 1 || d->data != d->array) {
1329
Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + alloc));
1332
x->size = qMin(alloc, d->size);
1333
::memcpy(x->array, d->data, x->size);
1334
x->array[x->size] = '\0';
1338
x = qAtomicSetPtr(&d, x);
1339
if (!x->ref.deref())
1342
Data *x = static_cast<Data *>(qRealloc(d, sizeof(Data) + alloc));
1351
void QByteArray::expand(int i)
1353
resize(qMax(i + 1, d->size));
1357
Prepends the byte array \a ba to this byte array and returns a
1358
reference to this byte array.
1362
QByteArray x("ship");
1363
QByteArray y("air");
1368
This is the same as insert(0, \a ba).
1370
\sa append(), insert()
1373
QByteArray &QByteArray::prepend(const QByteArray &ba)
1375
if (d == &shared_null || d == &shared_empty) {
1377
} else if (ba.d != &shared_null) {
1378
QByteArray tmp = *this;
1388
Prepends the string \a str to this byte array.
1391
QByteArray &QByteArray::prepend(const char *str)
1394
int len = qstrlen(str);
1395
if (d->ref != 1 || d->size + len > d->alloc)
1396
realloc(qAllocMore(d->size + len, sizeof(Data)));
1397
memmove(d->data+len, d->data, d->size);
1398
memcpy(d->data, str, len);
1400
d->data[d->size] = '\0';
1408
Prepends the character \a ch to this byte array.
1411
QByteArray &QByteArray::prepend(char ch)
1413
if (d->ref != 1 || d->size + 1 > d->alloc)
1414
realloc(qAllocMore(d->size + 1, sizeof(Data)));
1415
memmove(d->data+1, d->data, d->size);
1418
d->data[d->size] = '\0';
1423
Appends the byte array \a ba onto the end of this byte array.
1427
QByteArray x("free");
1428
QByteArray y("dom");
1433
This is the same as insert(size(), \a ba).
1435
This operation is typically very fast (\l{constant time}),
1436
because QByteArray preallocates extra space at the end of the
1437
character data so it can grow without reallocating the entire
1440
\sa operator+=(), prepend(), insert()
1443
QByteArray &QByteArray::append(const QByteArray &ba)
1445
if (d == &shared_null || d == &shared_empty) {
1447
} else if (ba.d != &shared_null) {
1448
if (d->ref != 1 || d->size + ba.d->size > d->alloc)
1449
realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1450
memcpy(d->data + d->size, ba.d->data, ba.d->size);
1451
d->size += ba.d->size;
1452
d->data[d->size] = '\0';
1457
/*! \fn QByteArray &QByteArray::append(const QString &str)
1461
Appends the string \a str to this byte array. The Unicode data is
1462
converted into 8-bit characters using QString::toAscii().
1464
If the QString contains non-ASCII Unicode characters, using this
1465
function can lead to loss of information. You can disable this
1466
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1467
applications. You then need to call QString::toAscii() (or
1468
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1469
explicitly if you want to convert the data to \c{const char *}.
1475
Appends the string \a str to this byte array.
1478
QByteArray& QByteArray::append(const char *str)
1481
int len = qstrlen(str);
1482
if (d->ref != 1 || d->size + len > d->alloc)
1483
realloc(qAllocMore(d->size + len, sizeof(Data)));
1484
memcpy(d->data + d->size, str, len + 1); // include null terminator
1493
Appends the character \a ch to this byte array.
1496
QByteArray& QByteArray::append(char ch)
1498
if (d->ref != 1 || d->size + 1 > d->alloc)
1499
realloc(qAllocMore(d->size + 1, sizeof(Data)));
1500
d->data[d->size++] = ch;
1501
d->data[d->size] = '\0';
1507
Inserts \a len bytes from the array \a arr at position \a pos and returns a
1508
reference the modified byte array.
1510
static inline QByteArray &qbytearray_insert(QByteArray *ba,
1511
int pos, const char *arr, int len)
1515
if (pos < 0 || len <= 0 || arr == 0)
1518
int oldsize = ba->size();
1519
ba->resize(qMax(pos, oldsize) + len);
1520
char *dst = ba->data();
1522
::memset(dst + oldsize, 0x20, pos - oldsize);
1524
::memmove(dst + pos + len, dst + pos,
1525
(oldsize - pos) * sizeof(char));
1526
memcpy(dst + pos, arr, len * sizeof(char));
1531
Inserts the byte array \a ba at index position \a i and returns a
1532
reference to this byte array.
1536
QByteArray ba("Meal");
1537
ba.insert(1, QByteArray("ontr"));
1541
\sa append(), prepend(), replace(), remove()
1544
QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1546
QByteArray copy(ba);
1547
return qbytearray_insert(this, i, copy.d->data, copy.d->size);
1551
\fn QByteArray &QByteArray::insert(int i, const QString &str)
1555
Inserts the string \a str at index position \a i in the byte
1556
array. The Unicode data is converted into 8-bit characters using
1559
If \a i is greater than size(), the array is first extended using
1562
If the QString contains non-ASCII Unicode characters, using this
1563
function can lead to loss of information. You can disable this
1564
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1565
applications. You then need to call QString::toAscii() (or
1566
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1567
explicitly if you want to convert the data to \c{const char *}.
1573
Inserts the string \a str at position \a i in the byte array.
1575
If \a i is greater than size(), the array is first extended using
1579
QByteArray &QByteArray::insert(int i, const char *str)
1581
return qbytearray_insert(this, i, str, qstrlen(str));
1587
Inserts character \a ch at index position \a i in the byte array.
1588
If \a i is greater than size(), the array is first extended using
1592
QByteArray &QByteArray::insert(int i, char ch)
1594
return qbytearray_insert(this, i, &ch, 1);
1598
Removes \a len bytes from the array, starting at index position \a
1599
pos, and returns a reference to the array.
1601
If \a pos is out of range, nothing happens. If \a pos is valid,
1602
but \a pos + \a len is larger than the size of the array, the
1603
array is truncated at position \a pos.
1607
QByteArray ba("Montreal");
1612
\sa insert(), replace()
1615
QByteArray &QByteArray::remove(int pos, int len)
1617
if (len <= 0 || pos >= d->size || pos < 0)
1620
if (pos + len >= d->size) {
1623
memmove(d->data + pos, d->data + pos + len, d->size - pos - len);
1624
resize(d->size - len);
1630
Replaces \a len bytes from index position \a pos with the byte
1631
array \a after, and returns a reference to this byte array.
1635
QByteArray x("Say yes!");
1641
\sa insert(), remove()
1644
QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1646
QByteArray copy(after);
1648
return insert(pos, copy);
1651
/*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1659
Replaces every occurrence of the byte array \a before with the
1660
byte array \a after.
1664
QByteArray ba("colour behaviour flavour neighbour");
1665
ba.replace(QByteArray("ou"), QByteArray("o"));
1666
// ba == "color behavior flavor neighbor"
1670
QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1672
if (isNull() || before == after)
1675
QByteArrayMatcher matcher(before);
1677
const int bl = before.d->size;
1678
const int al = after.d->size;
1684
while ((index = matcher.indexIn(*this, index)) != -1) {
1685
memcpy(d + index, after, al);
1689
} else if (al < bl) {
1693
while ((index = matcher.indexIn(*this, index)) != -1) {
1695
int msize = index - movestart;
1697
memmove(d + to, d + movestart, msize);
1704
memcpy(d + to, after, al);
1712
int msize = len - movestart;
1714
memmove(d + to, d + movestart, msize);
1715
resize(len - num*(bl-al));
1718
// the most complex case. We don't want to lose performance by doing repeated
1719
// copies and reallocs of the string.
1720
while (index != -1) {
1724
index = matcher.indexIn(*this, index);
1727
indices[pos++] = index;
1729
// avoid infinite loop
1736
// we have a table of replacement positions, use them for fast replacing
1737
int adjust = pos*(al-bl);
1738
// index has to be adjusted in case we get back into the loop above.
1741
int newlen = len + adjust;
1751
int movestart = indices[pos] + bl;
1752
int insertstart = indices[pos] + pos*(al-bl);
1753
int moveto = insertstart + al;
1754
memmove(d + moveto, d + movestart, (moveend - movestart));
1756
memcpy(d + insertstart, after, al);
1757
moveend = movestart - bl;
1765
/*! \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1768
Replaces every occurrence of the string \a before with the
1769
byte array \a after.
1773
/*! \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
1776
Replaces every occurrence of the byte array \a before with the
1780
/*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
1784
Replaces every occurrence of the string \a before with the byte
1785
array \a after. The Unicode data is converted into 8-bit
1786
characters using QString::toAscii().
1788
If the QString contains non-ASCII Unicode characters, using this
1789
function can lead to loss of information. You can disable this
1790
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1791
applications. You then need to call QString::toAscii() (or
1792
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1793
explicitly if you want to convert the data to \c{const char *}.
1796
/*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
1799
Replaces every occurrence of the string \a before with the string
1803
/*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
1807
Replaces every occurrence of the string \a before with the string
1814
Replaces every occurrence of the character \a before with the
1815
byte array \a after.
1818
QByteArray &QByteArray::replace(char before, const QByteArray &after)
1820
char b[2] = { before, '\0' };
1821
QByteArray cb = fromRawData(b, 1);
1822
return replace(cb, after);
1825
/*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
1829
Replaces every occurrence of the character \a before with the
1830
string \a after. The Unicode data is converted into 8-bit
1831
characters using QString::toAscii().
1833
If the QString contains non-ASCII Unicode characters, using this
1834
function can lead to loss of information. You can disable this
1835
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1836
applications. You then need to call QString::toAscii() (or
1837
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1838
explicitly if you want to convert the data to \c{const char *}.
1841
/*! \fn QByteArray &QByteArray::replace(char before, const char *after)
1845
Replaces every occurrence of the character \a before with the
1852
Replaces every occurrence of the character \a before with the
1856
QByteArray &QByteArray::replace(char before, char after)
1860
char *e = i + d->size;
1869
Splits the byte array into subarrays wherever \a sep occurs, and
1870
returns the list of those arrays. If \a sep does not match
1871
anywhere in the byte array, split() returns a single-element list
1872
containing this byte array.
1875
QList<QByteArray> QByteArray::split(char sep) const
1877
QList<QByteArray> list;
1880
while ((end = indexOf(sep, start)) != -1) {
1881
list.append(mid(start, end - start));
1884
list.append(mid(start));
1889
if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
1890
hashHaystack -= (a) << ol_minus_1; \
1894
Returns the index position of the first occurrence of the byte
1895
array \a ba in this byte array, searching forward from index
1896
position \a from. Returns -1 if \a ba could not be found.
1900
QByteArray x("sticky question");
1901
QByteArray y("sti");
1902
x.indexOf(y); // returns 0
1903
x.indexOf(y, 1); // returns 10
1904
x.indexOf(y, 10); // returns 10
1905
x.indexOf(y, 11); // returns -1
1908
\sa lastIndexOf(), contains(), count()
1911
int QByteArray::indexOf(const QByteArray &ba, int from) const
1913
const int l = d->size;
1914
const int ol = ba.d->size;
1915
if (from > d->size || ol + from > l)
1920
return indexOf(*ba.d->data, from);
1922
if (l > 500 && ol > 5)
1923
return QByteArrayMatcher(ba).indexIn(*this, from);
1925
const char *needle = ba.d->data;
1926
const char *haystack = d->data + from;
1927
const char *end = d->data + (l - ol);
1928
const uint ol_minus_1 = ol - 1;
1929
uint hashNeedle = 0, hashHaystack = 0;
1931
for (idx = 0; idx < ol; ++idx) {
1932
hashNeedle = ((hashNeedle<<1) + needle[idx]);
1933
hashHaystack = ((hashHaystack<<1) + haystack[idx]);
1935
hashHaystack -= *(haystack + ol_minus_1);
1937
while (haystack <= end) {
1938
hashHaystack += *(haystack + ol_minus_1);
1939
if (hashHaystack == hashNeedle && *needle == *haystack
1940
&& strncmp(needle, haystack, ol) == 0)
1941
return haystack - d->data;
1949
/*! \fn int QByteArray::indexOf(const QString &str, int from) const
1953
Returns the index position of the first occurrence of the string
1954
\a str in the byte array, searching forward from index position
1955
\a from. Returns -1 if \a str could not be found.
1957
The Unicode data is converted into 8-bit characters using
1960
If the QString contains non-ASCII Unicode characters, using this
1961
function can lead to loss of information. You can disable this
1962
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1963
applications. You then need to call QString::toAscii() (or
1964
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1965
explicitly if you want to convert the data to \c{const char *}.
1968
/*! \fn int QByteArray::indexOf(const char *str, int from) const
1972
Returns the index position of the first occurrence of the string
1973
\a str in the byte array, searching forward from index position \a
1974
from. Returns -1 if \a str could not be found.
1980
Returns the index position of the first occurrence of the
1981
character \a ch in the byte array, searching forward from index
1982
position \a from. Returns -1 if \a ch could not be found.
1986
QByteArray ba("ABCBA");
1987
ba.indexOf("B"); // returns 1
1988
ba.indexOf("B", 1); // returns 1
1989
ba.indexOf("B", 2); // returns 3
1990
ba.indexOf("X"); // returns -1
1993
\sa lastIndexOf(), contains()
1996
int QByteArray::indexOf(char ch, int from) const
1999
from = qMax(from + d->size, 0);
2000
if (from < d->size) {
2001
const char *n = d->data + from - 1;
2002
const char *e = d->data + d->size;
2011
Returns the index position of the last occurrence of the byte
2012
array \a ba in this byte array, searching backward from index
2013
position \a from. If \a from is -1 (the default), the search
2014
starts at the last byte. Returns -1 if \a ba could not be found.
2018
QByteArray x("crazy azimuths");
2019
QByteArray y("azy");
2020
x.lastIndexOf(y); // returns 6
2021
x.lastIndexOf(y, 6); // returns 6
2022
x.lastIndexOf(y, 5); // returns 2
2023
x.lastIndexOf(y, 1); // returns -1
2026
\sa indexOf(), contains(), count()
2029
int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2031
const int ol = ba.d->size;
2032
const int l = d->size;
2036
if (from < 0 || from > l)
2041
return lastIndexOf(*ba.d->data, from);
2043
const char *needle = ba.d->data;
2044
const char *haystack = d->data + from;
2045
const char *end = d->data;
2046
const uint ol_minus_1 = ol - 1;
2047
const char *n = needle + ol_minus_1;
2048
const char *h = haystack + ol_minus_1;
2049
uint hashNeedle = 0, hashHaystack = 0;
2051
for (idx = 0; idx < ol; ++idx) {
2052
hashNeedle = ((hashNeedle<<1) + *(n-idx));
2053
hashHaystack = ((hashHaystack<<1) + *(h-idx));
2055
hashHaystack -= *haystack;
2056
while (haystack >= end) {
2057
hashHaystack += *haystack;
2058
if (hashHaystack == hashNeedle && strncmp(needle, haystack, ol) == 0)
2059
return haystack-d->data;
2061
REHASH(*(haystack + ol));
2067
/*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2071
Returns the index position of the last occurrence of the string \a
2072
str in the byte array, searching backward from index position \a
2073
from. If \a from is -1 (the default), the search starts at the
2074
last (size() - 1) byte. Returns -1 if \a str could not be found.
2076
The Unicode data is converted into 8-bit characters using
2079
If the QString contains non-ASCII Unicode characters, using this
2080
function can lead to loss of information. You can disable this
2081
function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2082
applications. You then need to call QString::toAscii() (or
2083
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2084
explicitly if you want to convert the data to \c{const char *}.
2087
/*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2090
Returns the index position of the last occurrence of the string \a
2091
str in the byte array, searching backward from index position \a
2092
from. If \a from is -1 (the default), the search starts at the
2093
last (size() - 1) byte. Returns -1 if \a str could not be found.
2099
Returns the index position of the last occurrence of character \a
2100
ch in the byte array, searching backward from index position \a
2101
from. If \a from is -1 (the default), the search starts at the
2102
last (size() - 1) byte. Returns -1 if \a ch could not be found.
2106
QByteArray ba("ABCBA");
2107
ba.lastIndexOf("B"); // returns 3
2108
ba.lastIndexOf("B", 3); // returns 3
2109
ba.lastIndexOf("B", 2); // returns 1
2110
ba.lastIndexOf("X"); // returns -1
2113
\sa indexOf(), contains()
2116
int QByteArray::lastIndexOf(char ch, int from) const
2120
else if (from > d->size)
2123
const char *b = d->data;
2124
const char *n = d->data + from + 1;
2133
Returns the number of (potentially overlapping) occurrences of
2134
byte array \a ba in this byte array.
2136
\sa contains(), indexOf()
2139
int QByteArray::count(const QByteArray &ba) const
2143
if (d->size > 500 && ba.d->size > 5) {
2144
QByteArrayMatcher matcher(ba);
2145
while ((i = matcher.indexIn(*this, i + 1)) != -1)
2148
while ((i = indexOf(ba, i + 1)) != -1)
2157
Returns the number of (potentially overlapping) occurrences of
2158
string \a str in the byte array.
2161
int QByteArray::count(const char *str) const
2165
while ((i = indexOf(str, i + 1)) != -1)
2173
Returns the number of occurrences of character \a ch in the byte
2176
\sa contains(), indexOf()
2179
int QByteArray::count(char ch) const
2182
const char *i = d->data + d->size;
2183
const char *b = d->data;
2190
/*! \fn int QByteArray::count() const
2198
Returns true if this byte array starts with byte array \a ba;
2199
otherwise returns false.
2203
QByteArray url("ftp://ftp.trolltech.com/");
2204
if (url.startsWith("ftp:"))
2208
\sa endsWith(), left()
2210
bool QByteArray::startsWith(const QByteArray &ba) const
2212
if (d == ba.d || ba.d->size == 0)
2214
if (d->size < ba.d->size)
2216
return memcmp(d->data, ba.d->data, ba.d->size) == 0;
2221
Returns true if this byte array starts with string \a str;
2222
otherwise returns false.
2224
bool QByteArray::startsWith(const char *str) const
2228
int len = qstrlen(str);
2231
return qstrncmp(d->data, str, len) == 0;
2236
Returns true if this byte array starts with character \a ch;
2237
otherwise returns false.
2239
bool QByteArray::startsWith(char ch) const
2243
return d->data[0] == ch;
2247
Returns true if this byte array ends with byte array \a ba;
2248
otherwise returns false.
2252
QByteArray url("http://www.trolltech.com/index.html");
2253
if (url.endsWith(".html"))
2257
\sa startsWith(), right()
2259
bool QByteArray::endsWith(const QByteArray &ba) const
2261
if (d == ba.d || ba.d->size == 0)
2263
if (d->size < ba.d->size)
2265
return memcmp(d->data + d->size - ba.d->size, ba.d->data, ba.d->size) == 0;
2270
Returns true if this byte array ends with string \a str; otherwise
2273
bool QByteArray::endsWith(const char *str) const
2277
int len = qstrlen(str);
2280
return qstrncmp(d->data + d->size - len, str, len) == 0;
2285
Returns true if this byte array ends with character \a ch;
2286
otherwise returns false.
2288
bool QByteArray::endsWith(char ch) const
2292
return d->data[d->size - 1] == ch;
2296
Returns a byte array that contains the leftmost \a len bytes of
2299
The entire byte array is returned if \a len is greater than
2304
QByteArray x("Pineapple");
2305
QByteArray y = x.left(4);
2309
\sa right(), mid(), startsWith(), truncate()
2312
QByteArray QByteArray::left(int len) const
2318
return QByteArray(d->data, len);
2322
Returns a byte array that contains the rightmost \a len bytes of
2325
The entire byte array is returned if \a len is greater than
2330
QByteArray x("Pineapple");
2331
QByteArray y = x.right(5);
2335
\sa endsWith(), left(), mid()
2338
QByteArray QByteArray::right(int len) const
2344
return QByteArray(d->data + d->size - len, len);
2348
Returns a byte array containing \a len bytes from this byte array,
2349
starting at position \a pos.
2351
If \a len is -1 (the default), or \a pos + \a len >= size(),
2352
returns a byte array containing all bytes starting at position \a
2353
pos until the end of the byte array.
2357
QByteArray x("Five pineapples");
2358
QByteArray y = x.mid(5, 4); // y == "pine"
2359
QByteArray z = x.mid(5); // z == "pineapples"
2365
QByteArray QByteArray::mid(int pos, int len) const
2367
if (d == &shared_null || d == &shared_empty || pos >= d->size)
2368
return QByteArray();
2370
len = d->size - pos;
2375
if (len + pos > d->size)
2376
len = d->size - pos;
2377
if (pos == 0 && len == d->size)
2379
return QByteArray(d->data + pos, len);
2383
Returns a lowercase copy of the byte array. The bytearray is
2384
interpreted as a Latin-1 encoded string.
2388
QByteArray x("TROlltECH");
2389
QByteArray y = x.toLower();
2393
\sa toUpper(), {Note on 8-bit character comparisons}
2395
QByteArray QByteArray::toLower() const
2397
QByteArray s(*this);
2398
register uchar *p = reinterpret_cast<uchar *>(s.data());
2401
*p = QUnicodeTables::lower(*p);
2409
Returns an uppercase copy of the byte array. The bytearray is
2410
interpreted as a Latin-1 encoded string.
2414
QByteArray x("TROlltECH");
2415
QByteArray y = x.toUpper();
2419
\sa toLower(), {Note on 8-bit character comparisons}
2422
QByteArray QByteArray::toUpper() const
2424
QByteArray s(*this);
2425
register char *p = s.data();
2428
*p = QUnicodeTables::upper(*p);
2435
/*! \fn void QByteArray::clear()
2437
Clears the contents of the byte array and makes it empty.
2439
\sa resize(), isEmpty()
2442
void QByteArray::clear()
2444
if (!d->ref.deref())
2450
/*! \relates QByteArray
2452
Writes byte array \a ba to the stream \a out and returns a reference
2455
\sa {Format of the QDataStream operators}
2457
#ifndef QT_NO_DATASTREAM
2459
QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2461
if (ba.isNull() && out.version() >= 6) {
2462
out << (quint32)0xffffffff;
2465
return out.writeBytes(ba, ba.size());
2468
/*! \relates QByteArray
2470
Reads a byte array into \a ba from the stream \a in and returns a
2471
reference to the stream.
2473
\sa {Format of the QDataStream operators}
2476
QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2481
if (len == 0xffffffff)
2484
const quint32 Step = 1024 * 1024;
2485
quint32 allocated = 0;
2488
int blockSize = qMin(Step, len - allocated);
2489
ba.resize(allocated + blockSize);
2490
if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2492
in.setStatus(QDataStream::ReadPastEnd);
2495
allocated += blockSize;
2496
} while (allocated < len);
2500
#endif //QT_NO_DATASTREAM
2502
/*! \fn bool QByteArray::operator==(const QString &str) const
2504
Returns true if this byte array is equal to string \a str;
2505
otherwise returns false.
2507
The Unicode data is converted into 8-bit characters using
2510
The comparison is case sensitive.
2512
You can disable this operator by defining \c
2513
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2514
then need to call QString::fromAscii(), QString::fromLatin1(),
2515
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2516
you want to convert the byte array to a QString before doing the
2520
/*! \fn bool QByteArray::operator!=(const QString &str) const
2522
Returns true if this byte array is not equal to string \a str;
2523
otherwise returns false.
2525
The Unicode data is converted into 8-bit characters using
2528
The comparison is case sensitive.
2530
You can disable this operator by defining \c
2531
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2532
then need to call QString::fromAscii(), QString::fromLatin1(),
2533
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2534
you want to convert the byte array to a QString before doing the
2538
/*! \fn bool QByteArray::operator<(const QString &str) const
2540
Returns true if this byte array is lexically less than string \a
2541
str; otherwise returns false.
2543
The Unicode data is converted into 8-bit characters using
2546
The comparison is case sensitive.
2548
You can disable this operator by defining \c
2549
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2550
then need to call QString::fromAscii(), QString::fromLatin1(),
2551
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2552
you want to convert the byte array to a QString before doing the
2556
/*! \fn bool QByteArray::operator>(const QString &str) const
2558
Returns true if this byte array is lexically greater than string
2559
\a str; otherwise returns false.
2561
The Unicode data is converted into 8-bit characters using
2564
The comparison is case sensitive.
2566
You can disable this operator by defining \c
2567
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2568
then need to call QString::fromAscii(), QString::fromLatin1(),
2569
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2570
you want to convert the byte array to a QString before doing the
2574
/*! \fn bool QByteArray::operator<=(const QString &str) const
2576
Returns true if this byte array is lexically less than or equal
2577
to string \a str; otherwise returns false.
2579
The Unicode data is converted into 8-bit characters using
2582
The comparison is case sensitive.
2584
You can disable this operator by defining \c
2585
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2586
then need to call QString::fromAscii(), QString::fromLatin1(),
2587
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2588
you want to convert the byte array to a QString before doing the
2592
/*! \fn bool QByteArray::operator>=(const QString &str) const
2594
Returns true if this byte array is greater than or equal to string
2595
\a str; otherwise returns false.
2597
The Unicode data is converted into 8-bit characters using
2600
The comparison is case sensitive.
2602
You can disable this operator by defining \c
2603
QT_NO_CAST_FROM_ASCII when you compile your applications. You
2604
then need to call QString::fromAscii(), QString::fromLatin1(),
2605
QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2606
you want to convert the byte array to a QString before doing the
2610
/*! \fn bool operator==(const QByteArray &a1, const QByteArray &a2)
2615
Returns true if byte array \a a1 is equal to byte array \a a2;
2616
otherwise returns false.
2619
/*! \fn bool operator==(const QByteArray &a1, const char *a2)
2624
Returns true if byte array \a a1 is equal to string \a a2;
2625
otherwise returns false.
2628
/*! \fn bool operator==(const char *a1, const QByteArray &a2)
2633
Returns true if string \a a1 is equal to byte array \a a2;
2634
otherwise returns false.
2637
/*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2642
Returns true if byte array \a a1 is not equal to byte array \a a2;
2643
otherwise returns false.
2646
/*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2651
Returns true if byte array \a a1 is not equal to string \a a2;
2652
otherwise returns false.
2655
/*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2660
Returns true if string \a a1 is not equal to byte array \a a2;
2661
otherwise returns false.
2664
/*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2669
Returns true if byte array \a a1 is lexically less than byte array
2670
\a a2; otherwise returns false.
2673
/*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2678
Returns true if byte array \a a1 is lexically less than string
2679
\a a2; otherwise returns false.
2682
/*! \fn bool operator<(const char *a1, const QByteArray &a2)
2687
Returns true if string \a a1 is lexically less than byte array
2688
\a a2; otherwise returns false.
2691
/*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2696
Returns true if byte array \a a1 is lexically less than or equal
2697
to byte array \a a2; otherwise returns false.
2700
/*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2705
Returns true if byte array \a a1 is lexically less than or equal
2706
to string \a a2; otherwise returns false.
2709
/*! \fn bool operator<=(const char *a1, const QByteArray &a2)
2714
Returns true if string \a a1 is lexically less than or equal
2715
to byte array \a a2; otherwise returns false.
2718
/*! \fn bool operator>(const QByteArray &a1, const QByteArray &a2)
2723
Returns true if byte array \a a1 is lexically greater than byte
2724
array \a a2; otherwise returns false.
2727
/*! \fn bool operator>(const QByteArray &a1, const char *a2)
2732
Returns true if byte array \a a1 is lexically greater than string
2733
\a a2; otherwise returns false.
2736
/*! \fn bool operator>(const char *a1, const QByteArray &a2)
2741
Returns true if string \a a1 is lexically greater than byte array
2742
\a a2; otherwise returns false.
2745
/*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
2750
Returns true if byte array \a a1 is lexically greater than or
2751
equal to byte array \a a2; otherwise returns false.
2754
/*! \fn bool operator>=(const QByteArray &a1, const char *a2)
2759
Returns true if byte array \a a1 is lexically greater than or
2760
equal to string \a a2; otherwise returns false.
2763
/*! \fn bool operator>=(const char *a1, const QByteArray &a2)
2768
Returns true if string \a a1 is lexically greater than or
2769
equal to byte array \a a2; otherwise returns false.
2772
/*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
2775
Returns a byte array that is the result of concatenating byte
2776
array \a a1 and byte array \a a2.
2778
\sa QByteArray::operator+=()
2781
/*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
2786
Returns a byte array that is the result of concatenating byte
2787
array \a a1 and string \a a2.
2790
/*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
2795
Returns a byte array that is the result of concatenating byte
2796
array \a a1 and character \a a2.
2799
/*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
2804
Returns a byte array that is the result of concatenating string
2805
\a a1 and byte array \a a2.
2808
/*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
2813
Returns a byte array that is the result of concatenating character
2814
\a a1 and byte array \a a2.
2818
Returns a byte array that has whitespace removed from the start
2819
and the end, and which has each sequence of internal whitespace
2820
replaced with a single space.
2822
Whitespace means any character for which the standard C++
2823
isspace() function returns true. This includes the ASCII
2824
characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
2828
QByteArray ba(" lots\t of\nwhitespace\r\n ");
2830
// ba == "lots of whitespace";
2835
QByteArray QByteArray::simplified() const
2840
result.resize(d->size);
2841
const char *from = d->data;
2842
const char *fromend = from + d->size;
2844
char *to = result.d->data;
2846
while (from!=fromend && isspace(uchar(*from)))
2848
while (from!=fromend && !isspace(uchar(*from)))
2849
to[outc++] = *from++;
2855
if (outc > 0 && to[outc-1] == ' ')
2857
result.resize(outc);
2862
Returns a byte array that has whitespace removed from the start
2865
Whitespace means any character for which the standard C++
2866
isspace() function returns true. This includes the ASCII
2867
characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
2871
QByteArray ba(" lots\t of\nwhitespace\r\n ");
2873
// ba == "lots\t of\nwhitespace";
2876
Unlike simplified(), trimmed() leaves internal whitespace alone.
2880
QByteArray QByteArray::trimmed() const
2884
const char *s = d->data;
2885
if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
2888
int end = d->size - 1;
2889
while (start<=end && isspace(uchar(s[start]))) // skip white space from start
2891
if (start <= end) { // only white space
2892
while (end && isspace(uchar(s[end]))) // skip white space from end
2895
int l = end - start + 1;
2897
shared_empty.ref.ref();
2898
return QByteArray(&shared_empty, 0, 0);
2900
return QByteArray(s+start, l);
2904
Returns a byte array of size \a width that contains this byte
2905
array padded by the \a fill character.
2907
If \a truncate is false and the size() of the byte array is more
2908
than \a width, then the returned byte array is a copy of this byte
2911
If \a truncate is true and the size() of the byte array is more
2912
than \a width, then any bytes in a copy of the byte array
2913
after position \a width are removed, and the copy is returned.
2917
QByteArray x("apple");
2918
QByteArray y = x.leftJustified(8, '.'); // y == "apple..."
2921
\sa rightJustified()
2924
QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
2927
int len = qstrlen(d->data);
2928
int padlen = width - len;
2930
result.resize(len+padlen);
2932
memcpy(result.d->data, d->data, sizeof(char)*len);
2933
memset(result.d->data+len, fill, padlen);
2936
result = left(width);
2944
Returns a byte array of size \a width that contains the \a fill
2945
character followed by this byte array.
2947
If \a truncate is false and the size of the byte array is more
2948
than \a width, then the returned byte array is a copy of this byte
2951
If \a truncate is true and the size of the byte array is more
2952
than \a width, then the resulting byte array is truncated at
2957
QByteArray x("apple");
2958
QByteArray y = x.rightJustified(8, '.'); // y == "...apple"
2964
QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
2967
int len = qstrlen(d->data);
2968
int padlen = width - len;
2970
result.resize(len+padlen);
2972
memcpy(result.d->data+padlen, data(), len);
2973
memset(result.d->data, fill, padlen);
2976
result = left(width);
2983
bool QByteArray::isNull() const { return d == &shared_null; }
2987
Returns the byte array converted to a \c {long long} using base \a
2988
base, which is 10 by default and must be between 2 and 36, or 0.
2990
If \a base is 0, the base is determined automatically using the
2991
following rules: If the byte array begins with "0x", it is assumed to
2992
be hexadecimal; if it begins with "0", it is assumed to be octal;
2993
otherwise it is assumed to be decimal.
2995
Returns 0 if the conversion fails.
2997
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
2998
false; otherwise *\a{ok} is set to true.
3003
qlonglong QByteArray::toLongLong(bool *ok, int base) const
3005
#if defined(QT_CHECK_RANGE)
3006
if (base != 0 && (base < 2 || base > 36)) {
3007
qWarning("QByteArray::toLongLong: Invalid base %d", base);
3012
return QLocalePrivate::bytearrayToLongLong(constData(), base, ok);
3016
Returns the byte array converted to an \c {unsigned long long}
3017
using base \a base, which is 10 by default and must be between 2
3020
If \a base is 0, the base is determined automatically using the
3021
following rules: If the byte array begins with "0x", it is assumed to
3022
be hexadecimal; if it begins with "0", it is assumed to be octal;
3023
otherwise it is assumed to be decimal.
3025
Returns 0 if the conversion fails.
3027
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3028
false; otherwise *\a{ok} is set to true.
3033
qulonglong QByteArray::toULongLong(bool *ok, int base) const
3035
#if defined(QT_CHECK_RANGE)
3036
if (base != 0 && (base < 2 || base > 36)) {
3037
qWarning("QByteArray::toULongLong: Invalid base %d", base);
3042
return QLocalePrivate::bytearrayToUnsLongLong(constData(), base, ok);
3047
Returns the byte array converted to an \c int using base \a
3048
base, which is 10 by default and must be between 2 and 36, or 0.
3050
If \a base is 0, the base is determined automatically using the
3051
following rules: If the byte array begins with "0x", it is assumed to
3052
be hexadecimal; if it begins with "0", it is assumed to be octal;
3053
otherwise it is assumed to be decimal.
3055
Returns 0 if the conversion fails.
3057
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3058
false; otherwise *\a{ok} is set to true.
3061
QByteArray str("FF");
3063
int hex = str.toInt(&ok, 16); // hex == 255, ok == true
3064
int dec = str.toInt(&ok, 10); // dec == 0, ok == false
3070
int QByteArray::toInt(bool *ok, int base) const
3072
long v = toLongLong(ok, base);
3073
if (v < INT_MIN || v > INT_MAX) {
3082
Returns the byte array converted to an \c {unsigned int} using base \a
3083
base, which is 10 by default and must be between 2 and 36, or 0.
3085
If \a base is 0, the base is determined automatically using the
3086
following rules: If the byte array begins with "0x", it is assumed to
3087
be hexadecimal; if it begins with "0", it is assumed to be octal;
3088
otherwise it is assumed to be decimal.
3090
Returns 0 if the conversion fails.
3092
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3093
false; otherwise *\a{ok} is set to true.
3098
uint QByteArray::toUInt(bool *ok, int base) const
3100
ulong v = toULongLong(ok, base);
3110
Returns the byte array converted to a \c short using base \a
3111
base, which is 10 by default and must be between 2 and 36, or 0.
3113
If \a base is 0, the base is determined automatically using the
3114
following rules: If the byte array begins with "0x", it is assumed to
3115
be hexadecimal; if it begins with "0", it is assumed to be octal;
3116
otherwise it is assumed to be decimal.
3118
Returns 0 if the conversion fails.
3120
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3121
false; otherwise *\a{ok} is set to true.
3126
short QByteArray::toShort(bool *ok, int base) const
3128
long v = toLongLong(ok, base);
3129
if (v < SHRT_MIN || v > SHRT_MAX) {
3138
Returns the byte array converted to an \c {unsigned short} using base \a
3139
base, which is 10 by default and must be between 2 and 36, or 0.
3141
If \a base is 0, the base is determined automatically using the
3142
following rules: If the byte array begins with "0x", it is assumed to
3143
be hexadecimal; if it begins with "0", it is assumed to be octal;
3144
otherwise it is assumed to be decimal.
3146
Returns 0 if the conversion fails.
3148
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3149
false; otherwise *\a{ok} is set to true.
3154
ushort QByteArray::toUShort(bool *ok, int base) const
3156
ulong v = toULongLong(ok, base);
3157
if (v > USHRT_MAX) {
3167
Returns the byte array converted to a \c double value.
3169
Returns 0.0 if the conversion fails.
3171
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3172
false; otherwise *\a{ok} is set to true.
3175
QByteArray string("1234.56");
3176
double a = string.toDouble(); // a == 1234.56
3182
double QByteArray::toDouble(bool *ok) const
3184
return QLocalePrivate::bytearrayToDouble(constData(), ok);
3188
Returns the byte array converted to a \c float value.
3190
Returns 0.0 if the conversion fails.
3192
If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3193
false; otherwise *\a{ok} is set to true.
3198
float QByteArray::toFloat(bool *ok) const
3200
return float(toDouble(ok));
3204
Returns a copy of the byte array, encoded as Base64.
3207
QByteArray text("Qt is great!");
3208
text.toBase64(); // returns "UXQgaXMgZ3JlYXRcIQo="
3213
QByteArray QByteArray::toBase64() const
3215
const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3216
"ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3217
const char padchar = '=';
3221
tmp.resize(((d->size * 4) / 3) + 3);
3224
char *out = tmp.data();
3225
while (i < d->size) {
3227
chunk |= int(uchar(d->data[i++])) << 16;
3231
chunk |= int(uchar(d->data[i++])) << 8;
3232
if (i == d->size) padlen = 1;
3233
else chunk |= int(uchar(d->data[i++]));
3236
int j = (chunk & 0x00fc0000) >> 18;
3237
int k = (chunk & 0x0003f000) >> 12;
3238
int l = (chunk & 0x00000fc0) >> 6;
3239
int m = (chunk & 0x0000003f);
3240
*out++ = alphabet[j];
3241
*out++ = alphabet[k];
3242
if (padlen > 1) *out++ = padchar;
3243
else *out++ = alphabet[l];
3244
if (padlen > 0) *out++ = padchar;
3245
else *out++ = alphabet[m];
3248
tmp.truncate(out - tmp.data());
3252
/*! \fn QByteArray &QByteArray::setNum(int n, int base)
3254
Sets the byte array to the printed value of \a n in base \a base (10
3255
by default) and returns a reference to the byte array. The \a base can
3256
be any value between 2 and 36.
3262
ba.setNum(n); // ba == "63"
3263
ba.setNum(n, 16); // ba == "3f"
3266
\sa number(), toInt()
3269
/*! \fn QByteArray &QByteArray::setNum(uint n, int base)
3275
/*! \fn QByteArray &QByteArray::setNum(short n, int base)
3281
/*! \fn QByteArray &QByteArray::setNum(ushort n, int base)
3293
QByteArray &QByteArray::setNum(qlonglong n, int base)
3295
#if defined(QT_CHECK_RANGE)
3296
if (base < 2 || base > 36) {
3297
qWarning("QByteArray::setNum: Invalid base %d", base);
3301
QLocale locale(QLocale::C);
3302
*this = locale.d->longLongToString(n, -1, base).toLatin1();
3312
QByteArray &QByteArray::setNum(qulonglong n, int base)
3314
#if defined(QT_CHECK_RANGE)
3315
if (base < 2 || base > 36) {
3316
qWarning("QByteArray::setNum: Invalid base %d", base);
3320
QLocale locale(QLocale::C);
3321
*this = locale.d->unsLongLongToString(n, -1, base).toLatin1();
3327
Sets the byte array to the printed value of \a n, formatted in format
3328
\a f with precision \a prec, and returns a reference to the
3331
The format \a f can be any of the following:
3334
\header \i Format \i Meaning
3335
\row \i \c e \i format as [-]9.9e[+|-]999
3336
\row \i \c E \i format as [-]9.9E[+|-]999
3337
\row \i \c f \i format as [-]9.9
3338
\row \i \c g \i use \c e or \c f format, whichever is the most concise
3339
\row \i \c G \i use \c E or \c f format, whichever is the most concise
3342
With 'e', 'E', and 'f', \a prec is the number of digits after the
3343
decimal point. With 'g' and 'G', \a prec is the maximum number of
3344
significant digits (trailing zeroes are omitted).
3349
QByteArray &QByteArray::setNum(double n, char f, int prec)
3351
QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3355
flags = QLocalePrivate::CapitalEorX;
3360
form = QLocalePrivate::DFDecimal;
3363
form = QLocalePrivate::DFExponent;
3366
form = QLocalePrivate::DFSignificantDigits;
3369
#if defined(QT_CHECK_RANGE)
3370
qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3375
QLocale locale(QLocale::C);
3376
*this = locale.d->doubleToString(n, prec, form, -1, flags).toLatin1();
3380
/*! \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3383
Sets the byte array to the printed value of \a n, formatted in format
3384
\a f with precision \a prec, and returns a reference to the
3391
Returns a byte array containing the string equivalent of the
3392
number \a n to base \a base (10 by default). The \a base can be
3393
any value between 2 and 36.
3398
QByteArray::number(n); // returns "63"
3399
QByteArray::number(n, 16); // returns "3f"
3400
QByteArray::number(n, 16).upper(); // returns "3F"
3403
\sa setNum(), toInt()
3405
QByteArray QByteArray::number(int n, int base)
3417
QByteArray QByteArray::number(uint n, int base)
3429
QByteArray QByteArray::number(qlonglong n, int base)
3441
QByteArray QByteArray::number(qulonglong n, int base)
3450
Returns a byte array that contains the printed value of \a n,
3451
formatted in format \a f with precision \a prec.
3453
Argument \a n is formatted according to the \a f format specified,
3454
which is \c g by default, and can be any of the following:
3457
\header \i Format \i Meaning
3458
\row \i \c e \i format as [-]9.9e[+|-]999
3459
\row \i \c E \i format as [-]9.9E[+|-]999
3460
\row \i \c f \i format as [-]9.9
3461
\row \i \c g \i use \c e or \c f format, whichever is the most concise
3462
\row \i \c G \i use \c E or \c f format, whichever is the most concise
3465
With 'e', 'E', and 'f', \a prec is the number of digits after the
3466
decimal point. With 'g' and 'G', \a prec is the maximum number of
3467
significant digits (trailing zeroes are omitted).
3470
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
3476
QByteArray QByteArray::number(double n, char f, int prec)
3479
s.setNum(n, f, prec);
3484
Constructs a QByteArray that uses the first \a size characters in
3485
the array \a data. The bytes in \a data are \e not copied. The
3486
caller must be able to guarantee that \a data will not be deleted
3487
or modified as long as the QByteArray (or an unmodified copy of
3490
Any attempts to modify the QByteArray or copies of it will cause
3491
it to create a deep copy of the data, ensuring that the raw data
3494
Here's an example of how we can read data using a QDataStream on
3495
raw data in memory without requiring to copy the data into a
3499
static const char mydata[] = {
3500
0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
3501
0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
3506
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
3507
QDataStream in(&data, QIODevice::ReadOnly);
3511
\warning A byte array created with fromRawData() is \e not
3512
null-terminated, unless the raw data contains a 0 character at
3513
position \a size. While that does not matter for QDataStream or
3514
functions like indexOf(), passing the byte array to a function
3515
that accepts a \c{const char *} and expects it to be
3516
'\\0'-terminated leads into trouble.
3518
\sa data(), constData()
3521
QByteArray QByteArray::fromRawData(const char *data, int size)
3523
Data *x = static_cast<Data *>(qMalloc(sizeof(Data)));
3525
x->data = const_cast<char *>(data);
3531
x->alloc = x->size = size;
3533
return QByteArray(x, 0, 0);
3537
Returns a decoded copy of the Base64 array \a base64. For example:
3540
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXRcIQo=");
3541
text.data(); // returns "Qt is great!"
3546
QByteArray QByteArray::fromBase64(const QByteArray &base64)
3548
unsigned int buf = 0;
3551
tmp.resize((base64.size() * 3) / 4);
3554
for (int i = 0; i < base64.size(); ++i) {
3555
int ch = base64.at(i);
3558
if (ch >= 'A' && ch <= 'Z')
3560
else if (ch >= 'a' && ch <= 'z')
3562
else if (ch >= '0' && ch <= '9')
3572
buf = (buf << 6) | d;
3576
tmp[offset++] = buf >> nbits;
3577
buf &= (1 << nbits) - 1;
3582
tmp.truncate(offset);
3586
/*! \typedef QByteArray::ConstIterator
3590
/*! \typedef QByteArray::Iterator
3594
/*! \typedef QByteArray::const_iterator
3598
/*! \typedef QByteArray::iterator
3603
\fn QByteArray::QByteArray(int size)
3605
Use QByteArray(int, char) instead.
3610
\fn QByteArray QByteArray::leftJustify(uint width, char fill, bool truncate) const
3612
Use leftJustified() instead.
3616
\fn QByteArray QByteArray::rightJustify(uint width, char fill, bool truncate) const
3618
Use rightJustified() instead.
3622
\fn QByteArray& QByteArray::duplicate(const QByteArray& a)
3624
Use simple assignment instead. (QByteArray uses implicit sharing
3625
so if you modify a copy, only the copy is changed.)
3629
\fn QByteArray& QByteArray::duplicate(const char *a, uint n)
3631
Use simple assignment instead. (QByteArray uses implicit sharing
3632
so if you modify a copy, only the copy is changed.)
3636
\fn QByteArray& QByteArray::setRawData(const char *a, uint n)
3638
Use fromRawData() instead.
3642
\fn void QByteArray::resetRawData(const char *data, uint n)
3644
Use clear() instead.
3648
\fn QByteArray QByteArray::lower() const
3650
Use toLower() instead.
3654
\fn QByteArray QByteArray::upper() const
3656
Use toUpper() instead.
3660
\fn QByteArray QByteArray::stripWhiteSpace() const
3662
Use trimmed() instead.
3666
\fn QByteArray QByteArray::simplifyWhiteSpace() const
3668
Use simplified() instead.
3672
\fn int QByteArray::find(char c, int from = 0) const
3674
Use indexOf() instead.
3678
\fn int QByteArray::find(const char *c, int from = 0) const
3680
Use indexOf() instead.
3684
\fn int QByteArray::find(const QByteArray &ba, int from = 0) const
3686
Use indexOf() instead.
3690
\fn int QByteArray::findRev(char c, int from = -1) const
3692
Use lastIndexOf() instead.
3696
\fn int QByteArray::findRev(const char *c, int from = -1) const
3698
Use lastIndexOf() instead.
3702
\fn int QByteArray::findRev(const QByteArray &ba, int from = -1) const
3704
Use lastIndexOf() instead.
3708
\fn int QByteArray::find(const QString &s, int from = 0) const
3710
Use indexOf() instead.
3714
\fn int QByteArray::findRev(const QString &s, int from = -1) const
3716
Use lastIndexOf() instead.