QChar中的数据字节比从QChar到QByteArray的数据字节 [英] data bytes in QChar than from QChar to QByteArray

查看:506
本文介绍了QChar中的数据字节比从QChar到QByteArray的数据字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图在QChar中获取数据(8字节)而不是将其保存到QByteArray中,因为后来我想在我的函数中单独使用每个字节。

 QChar tempVar = *(QChar *)DeviceMsg.DATA; 



预期来自DeviceMsg.DATA的字节类似于00ff22ff55001188



我要找的是



 QByteArray qba; 
qba.data()[0] 00
qba.data()[1] ff
qba.data()[2] 22
qba.data()[3 ] ff
..



这里的问题是



如何从QChar转换为QByteArray?



感谢阅读问题任何帮助将不胜感激

解决方案

这将无法正常工作,因为你的input是一个包含16个字符的字符串(您的示例00ff22ff55001188)( QChar )。如果需要由两个字符表示的字节,则必须获得一个字符对并将其转换为一个字节,或者只是将整个字符串转换为64位值并将其拆分为字节。



一个可能的解决方案是(假设 DeviceMsg QString ,16个字符表示64-位十六进制值):

 QByteArray qba; 
qba.resize( 8 );
qulonglong val = DeviceMsg.toULongLong(NULL, 16 );
for int i = 0 ; i< 8 ; i ++)
{
// < span class =code-comment>获取低字节并将其存储在字节数组中
qba [i] = static_cast< char>(val& 0xFF);
// 下一个字节的移位
val>> = 8 ;
}







根据有关DeviceMsg的新信息(见下文评论) )没有必要使用 QChar ,解决方案非常简单(参见 http://doc.qt.io/qt-5/qbytearray.html#QByteArray-1 [ ^ ]):

 QByteArray qba((  const   char  *)DeviceMsg.DATA, sizeof (DeviceMsg.DATA)); 


Hi,
I am trying to get data(8 Bytes) in QChar than save it into QByteArray because later i want to use each byte separately in my function.

QChar tempVar=*(QChar*) DeviceMsg.DATA;


expected Bytes from DeviceMsg.DATA would be something like 00ff22ff55001188

what i am looking for is

QByteArray qba;
qba.data()[0]     00
qba.data()[1]     ff
qba.data()[2]     22
qba.data()[3]     ff
..


question here is

how to convert from QChar to QByteArray?

Thanks for reading Question any help would be appreciated

解决方案

This would not work as expected because your input is a string (your example "00ff22ff55001188") containing 16 characters (QChar). If you need the bytes represented by two characters, you must get a character pair and convert it to a byte or just convert the whole string to a 64-bit value and split that into bytes.

A possible solution would be (assuming DeviceMsg is a QString with 16 characaters representing a 64-bit hex value):

QByteArray qba;
qba.resize(8);
qulonglong val = DeviceMsg.toULongLong(NULL, 16);
for (int i = 0; i < 8; i++)
{
    // Get the low byte and store it in the byte array
    qba[i] = static_cast<char>(val & 0xFF);
    // Shift in next byte
    val >>= 8;
}



[EDIT]
According to the new information about DeviceMsg (see below comment) there is no need to use QChar and the solution is quite simple (see http://doc.qt.io/qt-5/qbytearray.html#QByteArray-1[^]):

QByteArray qba((const char *)DeviceMsg.DATA, sizeof(DeviceMsg.DATA));


这篇关于QChar中的数据字节比从QChar到QByteArray的数据字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆