boost crc每次产生不同的输出

时间:2018-11-21 08:55:14

标签: c++ boost crc16 catch-unit-test

背景

我正在尝试使用boost crc lib计算给定字节数组的CRC-16 / CRC2。

注意:我最擅长C ++开发

#include <iostream>
#include <vector>
#include <boost/crc.hpp>

namespace APP{
    class CrcUtil{
        public:
            static uint16_t crc16(const std::vector<uint8_t> input) {
                boost::crc_16_type result;
                result.process_bytes(&input, input.size());
                return result.checksum();
            }

            CrcUtil()=delete;
    };
};

我正在使用catch2作为测试框架。这是测试代码:

#include "catch.hpp"

#include "../include/crcUtil.h"

TEST_CASE("is crc calculation correct", "[crcUtil.h TESTS]"){
    std::vector<uint8_t> bytes = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
    auto expectedCRC2 = 0x3c9d;
    auto actualCRC2 = APP::CrcUtil::crc16(bytes);

    REQUIRE(expectedCRC2 == actualCRC2);
}

问题

每次运行测试时,计算出的CRC都是不同的。

首次运行:

/.../test/crcUtilTests.cpp:10: FAILED:
    REQUIRE( expectedCRC2 == actualCRC2 )
with expansion:
    15517 (0x3c9d) == 63180

第二次运行:

/.../test/crcUtilTests.cpp:10: FAILED:
    REQUIRE( expectedCRC2 == actualCRC2 )
with expansion:
    15517 (0x3c9d) == 33478

第N次运行:

/.../test/crcUtilTests.cpp:10: FAILED:
    REQUIRE( expectedCRC2 == actualCRC2 )
with expansion:
    15517 (0x3c9d) == 47016

问题

我的代码有问题吗?

为什么相同输入的CRC16不同?

如何为给定的字节数组可靠地计算CRC16?

1 个答案:

答案 0 :(得分:1)

&input

不会为您提供指向数据缓冲区的指针!它为您提供了一个指向vector对象本身的指针,因此您正在将该对象的内部解释为数据缓冲区。每次都会有所不同,因为它包含动态分配给实际数据缓冲区的指针之类的东西。

此外,vector的对象表示形式可能与input.size()的大小不同,并且可能也有一些padding bytes。因此,很可能您还通过读取未初始化的内存来调用Undefined Behaviour,这意味着您的程序完全无效,并且有任何可能发生的事情(包括看起来正常工作)。< / p>

使用input.data()获取指向所包含数据的指针,如下所示:

result.process_bytes(input.data(), input.size());