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。 –
謝謝。有效。現在我有另一個問題。 「反映的輸入」和「反映的結果」是什麼意思,我怎樣才能實現這些選項? –