用python搞个可视化界面:
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QMessageBox
# 生成 Modbus 格式的 CRC 校验码
def crc16_modbus(data):
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if (crc & 0x0001):
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
crc = format(crc, '04X')
# 将高位字节和低位字节交换位置
crc = crc[2:] + crc[:2]
return crc
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("CRC校验码计算器")
self.setGeometry(100, 100, 300, 200)
# 创建界面元素
self.label_input = QLabel("请输入数据(以空格分隔):", self)
self.label_input.setGeometry(20, 30, 200, 20)
self.input_data = QLineEdit(self)
self.input_data.setGeometry(30, 60, 240, 20)
self.btn_calculate = QPushButton("计算", self)
self.btn_calculate.setGeometry(30, 100, 240, 30)
self.btn_calculate.clicked.connect(self.calculate_crc)
self.label_output = QLabel("CRC校验码:", self)
self.label_output.setGeometry(20, 150, 200, 20)
self.output_data = QLabel("", self)
self.output_data.setGeometry(120, 150, 150, 20)
def calculate_crc(self):
# 获取输入数据
input_text = self.input_data.text().strip()
if not all(c in '0123456789ABCDEFabcdef ' for c in input_text):
QMessageBox.warning(self, "警告", "请输入有效的十六进制数!")
return
input_list = input_text.split(" ")
input_bytes = []
for num in input_list:
try:
input_bytes.append(int(num, 16)) # 将基数改为 16(十六进制)
except ValueError:
QMessageBox.warning(self, "警告", "请输入有效的十六进制数!")
return
# 计算 CRC
crc = crc16_modbus(input_bytes)
# 更新结果标签
self.output_data.setText(crc)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
来看效果: