转载自http://blog.sina.com.cn/s/blog_539d078401014eoh.html
QByteArray可以用来存储原始字节(包括‘\0’)和传统的8位‘\0'结束的字符串。它比使用const char*更方便。
通常它能保证数据末尾是'\0'空字符。当要存储二进制的原始数据时或者减少内存占用时,QByteArray特别合适。
除了QByteArray外,QT也用QString来存储字符串数据。QString储存16位Unicode双字节字符,当要转换成8位单字节字符时可以用 QString::toAscii()函数 (或 QString::toLatin1() 或 QString::toUtf8() 或QString::toLocal8Bit())。
一种初始化QByteArray变量的方法是简单传送一个 const char * 指针变量到构造函数. 例如下面的代码生成一个大小为5的包含字符串"Hello"字节数组:
QByteArray ba("Hello");
尽管数组size()函数返回是5,但数组包含一个额外的'\0'空字符。
QByteArray变量会进行const char *数据的深度拷贝。如果不需要深度拷贝,可以用函数QByteArray::fromRawData()来替代。
函数char * QBygeArray::data()会返回存储在byte数组中的数据指针。指针可用于读取或修改数组中的字节。数据总是以'\0'空字符结尾。字节的数目将返回size()+1。
对于字符型数组变量,如果赋值字符串,字符串结尾会置空字符。数组的数目为字符数加1。字符串的长度为字符数。例如:
char buffer[] = "Hello"
sizeof(buffer)=6
qstrlen(buffer)=5
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1]
strcpy(data, text.data());
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data(); // returns "Qt is great!"
A byte array created with fromRawData() is not null-terminated, unless the raw data contains a 0 character at position size.
static const char mydata[] = {
0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
...
0x6d, 0x5b
};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
Hexadecimal to decimal conversion
QString str = "0xED8788DC";
bool ok;
uint appId = str.toUInt(&ok,16); //appId contains 3985082588
Decimal to hexadecimal conversion
uint decimal = 3985082588;
QString hexadecimal;
haxadecimal.setNum(decimal,16); //now hexadecimal contains ED8788DC
QString to char * conversion
QString str;
char * data=str.toLatin1().data();
QString to char * conversion
char * data;
QString str(data.toLatin1());