unsigned short to unsigned char array in hex format
I have to send the message to server with following specs:
using MinGW on devices with embedded linux we use following code (in C), on our new device with QT environment using ARM unknown linux compiler I am unable to find the solution to perform this task, can anyone kindly help me to solve this issue.
For your reference I am pasting the working code of MinGW:
typedef unsigned short UWORD;
typedef unsigned char UBYTE;
void Calc2BytesHexLength(UBYTE * outBuf, UWORD len)
sprintf(buf, "%04x" , len);
QByteArray message("hello world!"); const QByteArray hexLen = QByteArray::number(static_cast<quint16>(message.size()),16); message.prepend(hexLen); if(hexLen.size()==1) message.prepend('0'); qDebug() << message; //print the formatted message
Thanks for your reply and solution, I will look into this solution and close accordingly.
Thanks for your response on this query, and sorry for my late reply.
The solution you pasted above is good for the values those are already in string form, whereas I need the hex values that I have done by using arithmetic division and remainder logic.
One more thing similar to this is that I need to print/debug the hex value of variable:
like : BYTE data = 0x01; // (where byte = unsigned char)
now I need to print on console as:
with MinGW we use this using:
UBYTE data = 0x01;
memset(debugData, 0, 50);
sprintf(debugData, "Data [%02X]", data);
@Kashif: If your data is in a QByteArray,
toHex()will help you.
I've changed @VRonin's suggestion a bit:
QByteArray binary("\x12\x34\x56\x78\x9A\xBC"); QByteArray message = binary.toHex(); //= "123456789abc" const QByteArray hexLen = QByteArray::number(message.size(),16); message.prepend(hexLen); if(hexLen.size()==1) message.prepend('0'); qDebug() << message; //print the formatted message
- I've removed the
static_castas I don't think it is needed for
QByteArray::number()doesn't have a field width specifier (unlike e.g.
QString::arg()has), so printing sizes below 10 needs the ugly
- If message is very long, prepending the lenght may be unperformant. In this case, creating a new byte array and appending may be better.
- If you need uppercase hex chars, call
- I've removed the
@aha_1980 : Thanks for your reply, my current problem is solved,