- uchar*与QByteArray类型
uchar转为QByteArray
QByteArray array;
unsigned char buf ;
array=QByteArray::fromRawData((char)buf,sizeof(buf));
QByteArray转为uchar
//一次性转换
buf = reinterpret_cast<unsigned char*>(array.data());
//单个数据转换
(unsigned char)array[0]
(unsigned char)array[1]
- char与QByteArray类型
char转换为QByteArray:
QByteArray array;
char buf;
array = QByteArray(buf, sizeof(buf)) // 必须加上数据长度,否则,数据会直接截断,丢失数据
QByteArray转为char
buf=array.data();
3、QString与QByteArray类型
QByteArray array;
QString s;
array = s.toLocal8Bit();
QByteArray转换为QString:
s = QString(array);
4、int 与QByteArray类型
int 转换为QByteArray:
int val;
QByteArray array;
array.resize(sizeof(val));
memcpy(array.data(), &val, sizeof(val));
QByteArray转换为int :
memcpy(&val, array.data(), sizeof(val));
5、int[] 与QByteArray类型
int[] 转换为QByteArray:
int val[10];
QByteArray array;
array.resize(sizeof(val));
memcpy(array.data(), &val, sizeof(val));
QByteArray转换为int[] :
memcpy(&val, array.data(), sizeof(val));
5、QByteArray与结构体之间的转换
** QByteArray转换为结构体:**
typedef struct{
unsigned char temp;
······
} CustomStruct
这里不是指针
QByteArray array_data;
QByteArray转为结构体
方法1
CustomStruct *struct_Data = reinterpret_cast<CustomStruct *>(array_data.data());
方法2
QByteArray read = client->readAll();
CustomStruct pdo1;
memset(&pdo1, 0, sizeof(CustomStruct));
memcpy(&pdo1, read.data(), sizeof(CustomStruct));
** 结构体转换为QByteArray:**
方法1
array_data.append((char*)&struct_Data,sizeof(struct_Data));
方法2
int datalen = sizeof(CustomStruct);
char src[sizeof(CustomStruct)];
memset(src, 0, datalen);
memcpy(src, cmd, datalen);
//struct to QByteArray
QByteArray sendData = QByteArray(src, datalen);