unsigned short to unsigned char array in hex format
-
Hi All,
I have to send the message to server with following specs:
lengthHEX(2Bytes)+messageusing 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)
{
char buf[4];
sprintf(buf, "%04x" , len);
AscHex (outBuf,buf,2);
}thanks
-
-
Hello Ronin,
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:
data [01]
with MinGW we use this using:UBYTE data = 0x01;
UBYTE debugData[50];
memset(debugData, 0, 50);
//----
sprintf(debugData, "Data [%02X]", data);
printf(debugData); -
@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
Notes:
- I've removed the
static_cast
as I don't think it is needed forQByteArray::number()
- Unfortunately
QByteArray::number()
doesn't have a field width specifier (unlike e.g.QString::arg()
has), so printing sizes below 10 needs the uglyprepend('0')
- 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
binary.toHex().toUpper()
- I've removed the
-
@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
Notes:
- I've removed the
static_cast
as I don't think it is needed forQByteArray::number()
- Unfortunately
QByteArray::number()
doesn't have a field width specifier (unlike e.g.QString::arg()
has), so printing sizes below 10 needs the uglyprepend('0')
- 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
binary.toHex().toUpper()
- I've removed the