网络报文CRC校验Test程序

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>

typedef unsigned char      uint8_t;

// CRC校验函数,多项式x16+x12+x2+1
unsigned short Crc16(const unsigned char *buffer, int buffer_length)
{
    unsigned short usCrc16 = 0x0000;  // 用 unsigned short
    unsigned char i = 0;

    while (buffer_length--)
    {
        for (i = 0x80; i != 0; i >>= 1)
        {
            if ((usCrc16 & 0x8000) != 0)
            {
                usCrc16 = usCrc16 << 1;
                usCrc16 = usCrc16 ^ 0x1005;//x16+x12+x2+1
            }
            else
            {
                usCrc16 = usCrc16 << 1;
            }
            if ((*buffer & i) != 0)
            {
                usCrc16 = usCrc16 ^ 0x1005;//x16+x12+x2+1
            }
        }
        buffer++;
    }
    return usCrc16;
}

//字符串转存到vector<>中
std::vector<uint8_t> hexStringToBytes(const std::string& hex) {
    std::vector<uint8_t> bytes;
    for (size_t i = 0; i < hex.length(); i += 2) {
        std::string byteString = hex.substr(i, 2);
        uint8_t byte = static_cast<uint8_t>(std::stoi(byteString, nullptr, 16));
        bytes.push_back(byte);
    }
    return bytes;
}

int main()
{

    std::string hexData = "00730101010000000001012003010801020000000200010214010300005343363130312032303136303136330003448001000041455342535020312e302e342e31303632342e522032303137303232380000000000000000000000000000000000000000000000000000000000000000000000";

    // 1. 转换成 vector
    std::vector<uint8_t> packet = hexStringToBytes(hexData);
    std::cout << "packet size = " << packet.size() << " bytes\n";

    // 2. 分配一个 C 数组
    unsigned char* data = new unsigned char[packet.size()];

    // 3. 拷贝数据
    memcpy(data, packet.data(), packet.size());
	
	// 4. 校验码计算
    auto rtn = Crc16(data,packet.size());

    // 打印成十六进制,高位在前(大端格式)
    std::cout << "CRC (big endian): 0x"
              << std::uppercase << std::hex << std::setw(4) << std::setfill('0')
              << rtn << std::endl;

    delete[] data;
}
posted @ 2025-10-10 11:08  江海余生  阅读(4)  评论(0)    收藏  举报