79 lines
2.8 KiB
C++
79 lines
2.8 KiB
C++
|
#include <iostream>
|
|||
|
#include <string>
|
|||
|
#include <iomanip>
|
|||
|
#include <sstream>
|
|||
|
|
|||
|
//校验函数
|
|||
|
unsigned int sumHexNumbersSkippingFirstTwo(const std::string& hexString) {
|
|||
|
std::istringstream iss(hexString);
|
|||
|
std::string hexNum;
|
|||
|
unsigned int sum = 0;
|
|||
|
|
|||
|
// 跳过前两个十六进制数(包括它们之间的空格,尽管在这个例子中可能不需要)
|
|||
|
iss >> std::hex >> hexNum; // 读取第一个FF
|
|||
|
iss >> hexNum; // 读取第二个FF(或空格后的下一个十六进制数)
|
|||
|
|
|||
|
// 现在开始累加剩下的十六进制数
|
|||
|
while (iss >> std::hex >> hexNum) {
|
|||
|
sum += std::stoul(hexNum, nullptr, 16);
|
|||
|
}
|
|||
|
|
|||
|
return -1-sum;
|
|||
|
}
|
|||
|
|
|||
|
// 函数:在16进制字符串中每两位插入分隔符
|
|||
|
std::string insertSeparators(const std::string& src, char separator) {
|
|||
|
std::string result;
|
|||
|
for (size_t i = 0; i < src.length(); i += 2) {
|
|||
|
if (i > 0) result += separator; // 在非第一个字符前插入分隔符
|
|||
|
result += src.substr(i, 2); // 添加两位16进制数
|
|||
|
}
|
|||
|
return result;
|
|||
|
}
|
|||
|
|
|||
|
std::string GetFrame() {
|
|||
|
int time, angle;
|
|||
|
std::string hexTime, hexAngle, finalString, hexCheck, hexCheck2;
|
|||
|
const std::string prefix = "FF FF 01 07 03 2A ";
|
|||
|
const std::string suffix = " 00";
|
|||
|
|
|||
|
// 获取用户输入
|
|||
|
std::cout << "请输入时间值: ";
|
|||
|
std::cin >> time;
|
|||
|
std::cout << "请输入角度值: ";
|
|||
|
std::cin >> angle;
|
|||
|
|
|||
|
// 计算角度的转换公式
|
|||
|
int convertedAngle = 4096 * (angle + 180) / 360;
|
|||
|
std::cout<<convertedAngle<<std::endl;
|
|||
|
// 将转换后的角度值和时间值转换为16进制字符串
|
|||
|
std::stringstream ss;
|
|||
|
ss << std::hex << std::uppercase;
|
|||
|
ss << std::setw(4) << std::setfill('0') << convertedAngle;
|
|||
|
std::cout<< "角度值转换:" <<ss.str()<<std::endl;
|
|||
|
hexAngle = ss.str();
|
|||
|
ss.str(""); // 清空stringstream以重用
|
|||
|
ss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << time; // 时间值始终为两位
|
|||
|
hexTime = ss.str();
|
|||
|
std::cout<< "时间值转换:" <<hexTime<<std::endl;
|
|||
|
// 在hexAngle中每两位插入空格(如果需要)
|
|||
|
hexAngle = insertSeparators(hexAngle, ' ');
|
|||
|
|
|||
|
// 拼接字符串
|
|||
|
finalString = prefix + hexAngle + " " + hexTime + suffix;
|
|||
|
|
|||
|
//校验和
|
|||
|
unsigned int sumResult = sumHexNumbersSkippingFirstTwo(finalString);
|
|||
|
std::cout << "校验和: " << sumResult << std::endl;
|
|||
|
ss.str(""); // 清空stringstream以重用
|
|||
|
ss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << sumResult;//校验和始终为两位
|
|||
|
hexCheck = ss.str();
|
|||
|
hexCheck2 = hexCheck.substr(hexCheck.length() - 2, 2);
|
|||
|
finalString = finalString + " " + hexCheck2;
|
|||
|
|
|||
|
// 输出结果
|
|||
|
std::cout << "发送的数据帧为: " << finalString << std::endl;
|
|||
|
|
|||
|
return finalString;
|
|||
|
}
|