unsigned short to unsigned char array in hex format

  • Hi All,

    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)
    char buf[4];
    sprintf(buf, "%04x" , len);
    AscHex (outBuf,buf,2);


  • QByteArray message("hello world!");
    const QByteArray hexLen = QByteArray::number(static_cast<quint16>(message.size()),16);
    qDebug() << message; //print the formatted message

  • Hello Ronin,

    Thanks for your reply and solution, I will look into this solution and close accordingly.


  • 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);

  • Qt Champions 2017

    @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);
    qDebug() << message; //print the formatted message


    1. I've removed the static_cast as I don't think it is needed for QByteArray::number()
    2. UnfortunatelyQByteArray::number() doesn't have a field width specifier (unlike e.g. QString::arg() has), so printing sizes below 10 needs the ugly prepend('0')
    3. If message is very long, prepending the lenght may be unperformant. In this case, creating a new byte array and appending may be better.
    4. If you need uppercase hex chars, call binary.toHex().toUpper()

  • @aha_1980 : Thanks for your reply, my current problem is solved,

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.