qt 二进制文件转换工具
qt二进制文件转化工具,注意点:写文件时候,对于非可显示字符,在qt5.9.3版本测试下,需要一个一个字符的写入,不然程序崩溃.
#include "mainwindow.h" #include "ui_mainwindow.h" #define VERSION "( V1.0.0)" #include <QFile> #include <QFileInfo> #include <QFileDialog> #include <QDateTime> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle(QStringLiteral("二进制文件查看转换工具")+VERSION); connect(ui->btn_readHex,&QPushButton::clicked,this,[=](){ QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral("数据读取"),".",tr("Exel file(*.txt *.hex *.bin)")); if(fileName.length()<=0) { return ; } ui->data->clear(); QFile file(fileName); bool isOK = file.open(QIODevice::ReadOnly); if(isOK == true){ QByteArray array = file.readAll(); QString strres = ""; for(int i=0;i<array.length();i++){ strres+=QString("00"+QString::number(array.at(i),16)).right(2); } ui->data->appendPlainText(strres); } file.close(); }); connect(ui->btn_readTXT,&QPushButton::clicked,this,[=](){ QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral("数据读取"),".",tr("Exel file(*.txt *.hex *.bin)")); if(fileName.length()<=0) { return ; } ui->data->clear(); QFile file(fileName); bool isOK = file.open(QIODevice::ReadOnly); if(isOK == true){ QByteArray array = file.readAll(); ui->data->appendPlainText(QString(array)); } file.close(); }); connect(ui->btn_saveTXT,&QPushButton::clicked,this,[=](){ QString name =QDateTime::currentDateTime().toString("yyyy_MM_dd__HH_mm_ss")+".txt"; QString fileName = QFileDialog::getSaveFileName(this,QStringLiteral("数据保存"),name,tr("Exel file(*.txt *.hex *.bin)")); if(fileName.length()<=0) { return ; } //创建文件对象 QFile file; //关联文件名字 file.setFileName(fileName); //打开文件,只写方式 if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QFile::Truncate)){ }//清空 file.close(); bool isOK = file.open(QIODevice::WriteOnly); if (isOK == true){ QString str = ui->data->toPlainText(); file.write(str.toStdString().data()); } file.close(); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_btn_saveHex_clicked() { QString name =QDateTime::currentDateTime().toString("yyyy_MM_dd__HH_mm_ss")+".hex"; QString fileName = QFileDialog::getSaveFileName(this,QStringLiteral("数据保存"),name,tr("Exel file(*.txt *.hex *.bin)")); if(fileName.length()<=0) { return ; } //创建文件对象 QFile file; //关联文件名字 file.setFileName(fileName); //打开文件,只写方式 if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QFile::Truncate)){ }//清空 file.close(); bool isOK = file.open(QIODevice::Append); QString str = ui->data->toPlainText(); for(int i=0;i<str.length()/2;i++){ unsigned char __d = str.mid(2*i,2).toInt(nullptr,16); file.write((char*)&__d,1); } file.close(); }
//
注意,在lambda表达式中,debug断点临时变量不会显示出来,得放置在一个函数中,才会正常显示
//