简体   繁体   English

如何将八位字节转换为QString?

[英]How to convert octet to QString?

I have a octet in my sources. 我的资料中有一个八位位组。 So I need to convert it to QString. 所以我需要将其转换为QString。

I tried QString str(a); 我尝试了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 ) 更新:a是八位位组,据我所读,它说“因为DDS_Octet相当于1字节(8位)”( http://community.rti.com/kb/what-max-number-octets-i-can -put-topicdata-builtin-topics

Update 2: 更新2:

its defined as a unsigned char (unsigned byte) 其定义为无符号字符(无符号字节)

Convert unsigned char to QString : unsigned char转换为QString

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

You probably should not convert an octet to a QString on its own. 你或许应该八位位组不能转换为一个QString自身。 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. 您可能会做的更好的是将其转换为Q(Latin1)Char并在需要将一些字符串操作放在一起的情况下使用。

Just doing it on its own looks impractical. 仅靠它自己做似乎是不切实际的。 Should you still insist on this, use the QString constructor as follows: 如果您仍然坚持这一点,请使用QString构造函数,如下所示:

main.cpp main.cpp中

#include <QString>
#include <QDebug>

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

main.pro 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. 让我不要对QString要求QCoreApplication实例正常工作大声疾呼,所以请让我们暂时忘记这一点。 :-) :-)

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 . 这将立即可用因为QString具有采用QChar构造函数,并且由于QChar具有采用unsigned char构造函数而可以隐式使用。

By the way, octet is almost exclusively 8 bits per byte these days. 顺便说一下,这些天八位字节几乎几乎是每个字节8位。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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