简体   繁体   中英

How to convert octet to QString?

I have a octet in my sources. So I need to convert it to QString.

I tried QString str(a); but it does not work. from what i read octet suppose to be a unsigned char

   a = 'A';

Update: a is the octet, from what i read it says "Since a DDS_Octet is equivalent to 1 Byte (8bits)" ( http://community.rti.com/kb/what-max-number-octets-i-can-put-topicdata-builtin-topics )

Update 2:

its defined as a unsigned char (unsigned byte)

Convert unsigned char to QString :

unsigned char a = 'A';
QString str = QString((QChar)a);

You probably should not convert an octet to a QString on its own. That will yield some superfluous conversion. What you would be better doing is probably convert it to Q(Latin1)Char and use that if you need to put some string manipulation together.

Just doing it on its own looks impractical. Should you still insist on this, use the QString constructor as follows:

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    unsigned char a = 'A';
    QString string(a);
    qDebug() << string;
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

"A"

Let me not start my rant about QString requiring a QCoreApplication instance to work properly, so please let us forget about that for a second. :-)

This will work out-of-the-box since QString has a constructor that takes QChar and that can be implicitly used since QChar has a constructor that takes an unsigned char .

By the way, octet is almost exclusively 8 bits per byte these days. I would not worry about it being handled differently, otherwise many software pieces could break underneath. Just see the code from the code that you linked, will you?

// DDS_Octet is defined to be 8 bits. If chars are not 8 bits
// on your system, this will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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