通信協議為保證數據傳輸准確,通常需要在數據幀后面加上校驗位,最常用的校驗方法是CRC。
最近遇到使用BCC校驗的項目,即需要將數據進行異或運算。
為了方便在沒有網絡的PC上進行BCC校驗計算,寫了如下一個小工具。(網上有不少在線計算的網站)
- 下載地址:藍奏雲:BCC校驗計算工具.exe
程序源碼
#include<iostream>
#include<sstream> //stringstream
#include<string>
#include<vector>
using namespace std;
char str_to_hex(char str)
{
char hex_result = 0;;
if (str < 0x3A)
hex_result = str - 0x30;//當輸入字符為0-9時
else
hex_result = str - 0x37;//當輸入字符為A-F時
return hex_result;
}
int main(void)
{
while (1)
{
puts("請輸入指令,以空格分隔:");
string str;
getline(cin, str);
stringstream input(str);//將獲得的string字符串放入string流input中
vector<string>data;
string tmp;//臨時字符串
while (getline(input, tmp, ' '))
data.push_back(tmp);
char bcc_result = 0;
vector<char> hex_trans; //vector可以自行擴大,不需要提前設置大小
for (int i = 0; i < data.size(); i++)
{
char temp= (str_to_hex(data[i][0]) << 4) + str_to_hex(data[i][1]);
hex_trans.push_back(temp);
bcc_result = bcc_result ^ hex_trans[i];
}
printf("\nBCC校驗值為:\n%x\n\n", bcc_result);
}
return 0;
}