2
我不知道这里是否提供此问题的正确位置,还是应该在codereview上提问。无论如何,我已经写了下面的代码来计算各种类型的CRC。其CRC16,CRC32和CRC64的结果与在线实施(例如here和here)相匹配。但对于CRC8,无论我设置参数,结果都不匹配。我不是循环冗余检查细节方面的专家,只是阅读了维基百科文章的一部分。谁能告诉我my code有什么问题?CRC计算模板适用于除CRC8以外的所有类型
#include <cstdio>
#include <string>
#include <stdint.h>
namespace crc
{
namespace templates
{
template <typename T> struct crcdata
{
T number = 0;
std::string toHex(void)
{
std::string s(2 * sizeof(T), '0');
for (T n = number, i = s.size(); n; n >>= 4)
s[--i] += (n & 0xF) > 9 ? (n % 16 - 9) | 16 : n % 16;
return s;
}
};
template <typename T, T polynomial, T init_cr, T final_cr>
class general_crc
{
public:
inline general_crc()
{
static T table[256];
/// build CRC lookup table. Skip the loop if already evaluated
for (int i = 0, b = 0; i < 256 && !table[255]; b = 8, i++)
{
table[i] = i;
while (b--) table[i] = (table[i] >> 1)^(table[i] & 1 ? polynomial : 0);
}
this->result.number = init_cr;
this->crc_table = (T const*)(void*)&table[0];
}
virtual ~general_crc(){}
private:
T const* crc_table;
crcdata <T> result;
void crc_calc(const void* buf, size_t size)
{
uint8_t* p = (uint8_t*)buf;
while (size--)
this->result.number = this->crc_table[(this->result.number^*p++) & 0xFF]^(this->result.number >> 8);
}
public:
/// crc of string
static crcdata <T> calculate(const std::string& s)
{
general_crc cr;
cr.crc_calc(s.c_str(), s.size());
cr.result.number ^= final_cr;
return cr.result;
}
};
}
typedef templates::general_crc <uint8_t, 0xAB, 0, 0> CRC8;
typedef templates::general_crc <uint16_t, 0xA001, 0, 0> CRC16;
typedef templates::general_crc <uint32_t, 0xEDB88320U, 0xFFFFFFFFU, 0xFFFFFFFFU> CRC32;
typedef templates::general_crc <uint64_t, 0xC96C5795D7870F42LLU, ~0LLU, ~0LLU> CRC64;
}
#include <iostream>
int main()
{
std::string test = "This is a test!!";
std::cout << crc::CRC8::calculate(test).toHex() << '\n';
std::cout << crc::CRC16::calculate(test).toHex() << '\n';
std::cout << crc::CRC32::calculate(test).toHex() << '\n';
std::cout << crc::CRC64::calculate(test).toHex() << '\n';
return 0;
}
我用[本网站](http://www.sunshine2k.de/coding/javascript/crc/crc_js.html)检查我的结果。在CRC8的情况下,它们不匹配。关于你的问题的第二部分,我不知道我应该得到什么。我只是用一些已经写好的代码来检查它们。 –
是的,它匹配。您需要将反映的多项式放入为0xd5。 –
谢谢。有效。现在我有另一个问题。 “反映的输入”和“反映的结果”是什么意思,我怎样才能实现这些选项? –