Files
cavity_LIBS/Public/crc16util.cpp
T
2026-11-06 14:45:09 +08:00

136 lines
3.1 KiB
C++

#include "crc16util.h"
#include <iostream>
#include <cstdint>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <cctype>
Crc16Util::Crc16Util()
{
}
// 计算Modbus CRC16校验值
uint16_t calculateCRC16(const uint8_t* data, size_t length) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; ++i) {
crc ^= static_cast<uint16_t>(data[i]);
for (size_t j = 0; j < 8; ++j) {
if ((crc & 0x0001) != 0) {
crc >>= 1;
crc ^= 0xA001;
}
else {
crc >>= 1;
}
}
}
return crc;
}
uint8_t hexToUint8(const std::string& hexStr) {
// 检查字符串长度
if (hexStr.length() < 2) {
return 0;
}
// 检查字符是否有效
char c1 = hexStr[0];
char c2 = hexStr[1];
// 转换为大写并验证是否为有效的十六进制字符
c1 = toupper(c1);
c2 = toupper(c2);
if (!((c1 >= '0' && c1 <= '9') || (c1 >= 'A' && c1 <= 'F')) ||
!((c2 >= '0' && c2 <= '9') || (c2 >= 'A' && c2 <= 'F'))) {
return 0;
}
uint8_t highNibble = (c1 >= 'A') ? (c1 - 'A' + 10) : (c1 - '0');
uint8_t lowNibble = (c2 >= 'A') ? (c2 - 'A' + 10) : (c2 - '0');
return (highNibble << 4) | lowNibble;
}
std::vector<uint8_t> splitAndConvertToHex(const std::string& input) {
std::vector<uint8_t> result;
// 检查输入字符串是否为空
if (input.empty()) {
return result;
}
std::stringstream ss(input);
std::string token;
while (ss >> token) {
// 检查token是否有效(至少2个字符)
if (token.length() >= 2) {
try {
uint8_t value = hexToUint8(token);
result.push_back(value);
} catch (...) {
// 如果转换失败,跳过这个token
continue;
}
}
}
return result;
}
std::string Crc16Util::getCRC16(std::string cmdHex){
// 添加空字符串检查
if (cmdHex.empty()) {
return "0000";
}
std::vector<uint8_t> hexArray = splitAndConvertToHex(cmdHex);
// 检查转换后的数组是否为空
if (hexArray.empty()) {
return "0000";
}
uint8_t* data = hexArray.data();
size_t size = hexArray.size();
// 计算CRC16校验值
uint16_t crc = calculateCRC16(data, size);
// 交换高低字节
uint16_t swappedCRC = ((crc & 0xFF) << 8) | ((crc & 0xFF00) >> 8);
std::stringstream ss;
ss << std::hex << std::setw(4) << std::setfill('0') << swappedCRC;
// 确保返回的字符串不为空
std::string result = ss.str();
if (result.empty()) {
return "0000";
}
return result;
// uint8_t data[] = { 0x5A, 0x01, 0x01, 0xA1, 0x01 };
// // 计算CRC16校验值
// uint16_t crc = calculateCRC16(data, sizeof(data));
// // 交换高低字节
// uint16_t swappedCRC = ((crc & 0xFF) << 8) | ((crc & 0xFF00) >> 8);
// // 输出校验值
// std::cout << "CRC16: 0x" << std::hex << swappedCRC << std::endl;
// return "";
}