BCC校验计算工具,附源码

通信协议为保证数据传输准确,通常需要在数据帧后面加上校验位,最常用的校验方法是CRC。
最近遇到使用BCC校验的项目,即需要将数据进行异或运算。
为了方便在没有网络的PC上进行BCC校验计算,写了如下一个小工具。(网上有不少在线计算的网站)

程序源码

#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;
}
posted @ 2022-01-27 15:26  中庭之园  阅读(1361)  评论(0编辑  收藏  举报