cpp
复制代码
#include "BtD_DtB_converter.h"
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qstring.h>
# pragma execution_character_set("utf-8")
BtD_DtB_converter::BtD_DtB_converter(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
this->setFixedSize(780, 400);
//创造两个转换按钮
QPushButton* convert1 = new QPushButton(this);
convert1->setGeometry(300, 100, 110, 50);
convert1->setText("二进制到十进制");
QPushButton* convert2 = new QPushButton(this);
convert2->setGeometry(300, 200, 110, 50);
convert2->setText("十进制到二进制");
//创造四个输入框LineEdit
QLineEdit* B_to_D_start = new QLineEdit(this);
B_to_D_start->setGeometry(100, 100, 100, 50);
QLineEdit* B_to_D_end = new QLineEdit(this);
B_to_D_end->setGeometry(500, 100, 100, 50);
QLineEdit* D_to_B_start = new QLineEdit(this);
D_to_B_start->setGeometry(100, 200, 100, 50);
QLineEdit* D_to_B_end = new QLineEdit(this);
D_to_B_end->setGeometry(500, 200, 100, 50);
//连接两个点击信号和槽函数
//二进制转换为十进制
connect(convert1, &QPushButton::clicked, [=]()
{
QString str_start = B_to_D_start->text();
//先查找是否有小数点
//如果没有小数点 只使用int数据类型存放即可
double NUM_END = 0;
double power = 1;
if (str_start.indexOf('.') == -1)
{
for (int i = str_start.length()-1; i >= 0; i--)
{
NUM_END += power * (str_start[i] == '1' ? 1:0);
power *= 2;
}
}
//最后显示在右边的搜索框中
else
{
power = 1 / (pow(2, str_start.length() - 1 - str_start.indexOf('.')));
for (int i = str_start.length() - 1; i > str_start.indexOf('.'); i--)
{
NUM_END += power * (str_start[i] == '1' ? 1 : 0);
power *= 2;
}
//计算小数部分结束,计算整数部分
power = 1;
for (int i = str_start.indexOf('.') - 1; i >= 0; i--)
{
NUM_END += power * (str_start[i] == '1' ? 1 : 0);
power *= 2;
}
}
B_to_D_end->setText(QString::number(NUM_END));
});
//十进制转换为二进制
connect(convert2, &QPushButton::clicked, [=]()
{
//如果没有小数点
QString str_start = D_to_B_start->text();
QString str_end = "";
//先查找是否有小数点
//如果没有小数点 只使用int数据类型存放即可
int NUM_END = 0;
int power = 2;
if (str_start.indexOf('.') == -1)
{
int NUM = str_start.toInt();
for (; NUM != 0; )
{
str_end.append(QString::number(NUM % 2));
NUM /= 2;
}
}
//如果有小数点
else
{
double NUM2 = str_start.toDouble();
int NUM = NUM2;//NUM为整数部分,与前兼容
NUM2 = NUM2 - NUM;//保留的小数部分后面进行处理.
for (; NUM != 0; )
{
str_end.append(QString::number(NUM % 2));
NUM /= 2;
}
//反转
for (int i = 0; i < str_end.length() / 2; i++)
{
QChar temp = str_end[i];
str_end[i] = str_end[str_end.length() - 1 - i];
str_end[str_end.length() - 1 - i] = temp;
}
//添加小数点
str_end.append('.');
//添加小数部分
int NUMofLeft;//乘2后的整数部分
for (; NUM2 != 0; )
{
NUM2 *= 2;
NUMofLeft = NUM2;
str_end.append(QString::number(NUMofLeft));
NUM2 = NUM2 - NUMofLeft;//减去整数部分.
}
D_to_B_end->setText((str_end));
return;
}
//最后显示在右边的搜索框中 注意要反转 注意:使用的是QChar而不是QChar的引用!
for (int i = 0; i < str_end.length()/2; i++)
{
QChar temp = str_end[i];
str_end[i] = str_end[str_end.length() - 1 - i];
str_end[str_end.length() - 1 - i] = temp;
}
D_to_B_end->setText((str_end));
});
}
BtD_DtB_converter::~BtD_DtB_converter()
{}