簡體   English   中英

如何根據查找表生成 CRC7?

[英]How to generate CRC7 based on lookup table?

我正在嘗試使用預生成的查找表來實現CRC-7/MMC校驗和。 這是到目前為止的代碼:

#include <iostream>
#include <string>
#include <cstdint>

using namespace std;

/* CRC-7/MMC
Poly: 0x09
Xorout: NO
Init: 0x00
Check value: 0x75 for "123456789"
*/

uint16_t CRC7_table[256];

void generate_crc7_table() {
    uint16_t byte;
    for (uint16_t i = 0; i < 256; i++) {
        byte = i;
        for (uint16_t bit = 0; bit < 8; bit++) {
            if (byte & 1) { //if lsb is 1 
                byte >>= 1;
                byte ^= 0x09;
            }
            else
                byte >>= 1;
        }
        CRC7_table[i] = byte >> 1; //to drop off MSB
    }
}

uint16_t crc7(string input) {
    uint16_t reg = 0;
    uint16_t b;

    for (uint16_t i = 0; i < input.length(); i++) {
        b = (input[i] ^ reg) & 0xFF;
        reg = (reg >> 1) ^ CRC7_table[b];
    }
    return reg;
}


int main()
{
    generate_crc7_table();
    cout << hex << crc7("123456789") << endl;
    return 0;
}

但它給出了錯誤的輸出。 我應該得到 0x75 但我得到 0x07。 我用這個網站來檢查輸出。 任何建議或想法都將受到高度贊賞。 謝謝。

請注意,您指向的 CRC 定義包括refin=false refout=false 該 CRC 沒有反映,因此它是用左移而不是右移計算的。

鑒於此,並且 CRC 的長度小於 8 位,您還希望將 7 位保留在用於計算的字節的頂部,而不是底部。 即位 1 到 7,而不是位 0 到 6。然后多項式也上移一位以進行表格計算。

這允許表驅動的逐字節計算簡單地將每個消息字節排他或進入用於計算的字節。 如果要返回低 7 位的 CRC,可以在最后將其下移一位。

示例( 0x120x09上移一位):

#include <iostream>
#include <string>

uint8_t table[256];

void make_table() {
    uint8_t octet = 0;
    do {
        uint8_t crc = octet;
        for (int k = 0; k < 8; k++)
            crc = crc & 0x80 ? (crc << 1) ^ 0x12 : crc << 1;
        table[octet++] = crc;
    } while (octet);
}

uint8_t crc7(std::string const& input) {
    uint8_t crc = 0;
    for (auto octet : input)
        crc = table[crc ^ octet];
    return crc >> 1;
}

int main() {
    make_table();
    std::cout << std::hex << (unsigned)crc7("123456789") << '\n';
}

crcany將根據定義為您生成 CRC 代碼。 由於您的 CRC-7/MMC 在 Greg 的目錄中,因此 crcany 將立即生成該代碼以及其中定義的其他 100 多個 CRC。 生成的代碼包括按位、按字節和按字計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM