c++ - boost crc 每次产生不同的输出
问题描述
背景
我正在尝试使用 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?
解决方案
&input
这不会给你一个指向数据缓冲区的指针!它为您提供了指向vector
对象本身的指针,因此您将该对象的内部解释为数据缓冲区。每次都会有所不同,因为它包含动态分配的指向真实数据缓冲区的指针之类的东西。
此外, 的对象表示vector
可能与 的大小不同input.size()
,并且也可能有一些填充字节。所以很可能您还通过读取未初始化的内存来调用未定义的行为,这意味着您的程序完全无效并且任何事情都可能发生(包括看起来正常工作)。
用于input.data()
获取指向所包含数据的指针,如下所示:
result.process_bytes(input.data(), input.size());
推荐阅读
- screen-resolution - 网站元素被隐藏在 125% 推荐的笔记本电脑缩放
- ios - 在文本文件中复制调查并粘贴到我的应用程序中
- scala - Kafka Streams:了解 groupByKey 和 windowedBy
- python - 如何阻止我的图表的标签出现在图表内?
- c# - DI 和基类
- javascript - 使用 getter 在 React 组件中渲染另一个组件是一种好习惯吗?
- php - 从 Docker 容器使用 localhost 连接到 MariaDB
- javafx - 是否可以在 ZuluFX for Mac 上使用 javapackager
- python-2.7 - flask_wtf SelectField(错误:选择无效)
- php - 我的php中的数组到字符串转换问题