Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted
Updated 10-Dec-15 22:02pm
v2
Comments
Richard MacCutchan 11-Dec-15 4:21am    
Can you not create the QByteArray direct from the DATA field?
XamBEE 11-Dec-15 10:04am    
DATA is not string its 8 Byte

typedef struct
{
DWORD ID;
canMSGTYPE MSGTYPE;
BYTE LEN;
BYTE DATA[8];
} CANMsg;

1 solution

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):
C++
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[^]):
C++
QByteArray qba((const char *)DeviceMsg.DATA, sizeof(DeviceMsg.DATA));
 
Share this answer
 
v4
Comments
XamBEE 11-Dec-15 10:01am    
Input is not string its 8 Byte data

typedef struct
{
DWORD ID;
canMSGTYPE MSGTYPE;
BYTE LEN;
BYTE DATA[8];
} CANMsg;
DeviceMsg.DATA is 8 Byte not QString
Jochen Arndt 11-Dec-15 10:16am    
See my updated solution.
XamBEE 11-Dec-15 10:28am    
What does this error message mean?
Call of overloaded function 'QByteArray(BYTE[8], unsigned int)' is ambguous
Jochen Arndt 11-Dec-15 10:33am    
Try casting as in my updated example.
[EDIT]
How is BYTE defined?
I assumed char, unsigned char, int8_t, uint8_t or something similar.
XamBEE 11-Dec-15 10:37am    
Thanks,
would be nice if you can elaborate it for clarification.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900