Qt 中字符串转二进制中的一个Bug

唐老师代码如下:

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFile file("C:/Users/hp/Desktop/test.hex");

    if( file.open(QIODevice::WriteOnly) )
    {
        QString dt = "D.T.Software";
        double value = 3.14;

        file.write(dt.toStdString().c_str());
        file.write(reinterpret_cast<char*>(&value), sizeof(value));

        file.close();
    }

    if( file.open(QIODevice::ReadOnly) )
    {
        QString dt = "";
        double value = 0;

        dt = QString(file.read(12));
        file.read(reinterpret_cast<char*>(&value), sizeof(value));

        file.close();

        qDebug() << dt;
        qDebug() << value;
    }
    
    return a.exec();
}

其中的将字符串写进二进制文件的用法,在Qtcreator4.5.1中没实现的了。

查阅资网上信息后,将代码改为:

    if( file.open(QIODevice::WriteOnly) )
    {
        QString dt = "willwilling";
        double value = 3.14;

        file.write( dt.toLatin1() );
        file.write(reinterpret_cast<char*>(&value), sizeof(value) );

        file.close();
    }

输出正常。

toLatin1():

QByteArray QString::toLatin1 () const

Returns a Latin-1 representation of the string as a QByteArray.

The returned byte array is undefined if the string contains non-Latin1 characters. Those characters may be suppressed or replaced with a question mark.

See also fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), and QTextCodec.

Latin1是ISO-8859-1的别名,有些环境下写作Latin-1。ISO-8859-1编码是单字节编码,向下兼容ASCII,其编码范围是0x00-0xFF,0x00-0x7F之间完全和ASCII一致,0x80-0x9F之间是控制字符,0xA0-0xFF之间是文字符号。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值