简体   繁体   English

Qt-将QString转换为QByteArray的索引-将设备ID分为3个索引

[英]Qt - Converting QString to Indices of QByteArray - Dividing device ID into 3 indices

I am using QtSerialPort to send serial messages across a COM port to an INSTEON PowerLinc 2413U Modem. 我正在使用QtSerialPort通过COM端口将串行消息发送到INSTEON PowerLinc 2413U调制解调器。 I can hardcode and send messages just fine, however I need to send the same message using variable device IDs. 我可以硬编码并发送消息,但是我需要使用可变设备ID发送相同的消息。 The following is the structure I used to send static messages: 以下是我用来发送静态消息的结构:

QByteArray msg;
bool msgStatus;   

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = 0x1B;
msg[3] = 0xE9;
msg[4] = 0x4B;
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

Index positions 2,3,and 4 represent the device ID. 索引位置2、3和4代表设备ID。 "1BE94B" in this instance. 在这种情况下为“ 1BE94B”。 My function accepts the device ID that the action should be executed for via QString. 我的函数接受应通过QString执行操作的设备ID。

How can I convert the QString to fit the needed structure of 3 indices. 如何将QString转换为适合3个索引的结构。 I successfully get each byte of the 3 byte address using the following: 我使用以下命令成功获取了3字节地址中的每个字节:

devID.mid(0,2)
devID.mid(2,2)
devID.mid(4,2)

My Target implementation is for the QByteArray to look like this: 我的Target实现是让QByteArray看起来像这样:

QByteArray msg;
bool msgStatus;   

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = devID.mid(0,2)
msg[3] = devID.mid(2,2)
msg[4] = devID.mid(4,2)
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

I have tried many different conversions schemes, but have been unable to resolve what I need. 我尝试了许多不同的转换方案,但是无法解决我所需要的。 Ultimately my msg should be structured as: 最终,我的msg应该构造为:

    02621DE94B151300

The only way I have successfully seen the intended device action is by individually assigning each byte in the QByteArray, using msg.append() does not seem to work. 我成功看到预期的设备操作的唯一方法是使用msg.append()似乎不起作用,分别分配QByteArray中的每个字节。

Thank you for your suggestions! 谢谢你的建议!

Part of the problem here is that QString is unicode/short based and not char based. 问题的一部分在于QString是基于unicode / short而不是基于char的。 For me it works when I use toLocal8Bit 对我来说,当我使用toLocal8Bit时,它可以工作

QByteArray id;
idd.resize(3);
id[0] = 0x1B;
id[1] = 0xE9;
id[2] = 0x4B;

QString devId( bytes );

QByteArray msg;
msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg.replace( 2, 3, devId.toLocal8Bit() );
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;

If your id is text, and not bytes, then the fromHex must be added: 如果您的ID是文本,而不是字节,则必须添加fromHex:

QString devId( "1BE94B" );
msg.replace( 2, 3, QByteArray::fromHex( devId.toLocal8Bit() ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM