簡體   English   中英

驗證 CRC32 校驗和

[英]Validating CRC32 checksum

我能夠成功生成與預期的 output 匹配的 CRC32。 但是,當我嘗試將帶有校驗和 C(由 CRC32 函數生成)的消息 M 插入同一個 CRC32 生成器時,我無法獲得預期的 output 0x00000000。

My CRC32 generator is basically just the code here ( https://lxp32.github.io/docs/a-simple-example-crc32-calculation/ ), with an additional function argument for the checksum, since the message and checksum in my箱子在收到時位於單獨的 memory 位置。

uint32_t crc32(const char* s, size_t n, uint32_t checksum) {
    uint32_t crc = 0xFFFFFFFF;
    size_t i; size_t j;

    for (i = 0; i < n; i++) {
        char ch = s[i];
        uint32_t t = (ch ^ crc) & 0xFF;
        crc = (crc >> 8) ^ crc32_table[t];
    }

    if (i & 1) { // if i ended odd, write a 0x00 pad bit
        uint32_t t = (0x00 ^ crc) & 0xFF;
        crc = (crc >> 8) ^ crc32_table[t];
    }

    // include checksum bits if not 0
    if (checksum) {
        for (j = 0; j < 4; j++) {
            char ch = (checksum & 0xFF);
            uint32_t t = (ch ^ crc) & 0xFF;
            crc = (crc >> 8) ^ crc32_table[t];
            checksum >>= 8;
        }
    }
    else {
        // append 32-bits of 0's
        for (j = 0; j < 4; j++) {
            uint32_t t = (0x00 ^ crc) & 0xFF;
            crc = (crc >> 8) ^ crc32_table[t];
        }
    }
    return ~crc;
}

bool validate_crc32(const char* msg, size_t n, uint32_t checksum) {
    uint32_t res = crc32(msg, n, checksum);
    return res == 0;
}

CRC32 輸入 1:0x61 0x62 0x63 0x64 0x00 0x00 0x00 0x00

CRC32 Output 1:0x 87988EF9

CRC32 輸入 2:0x61 0x62 0x63 0x64 0x87 0x98 0x8E 0xF9

CRC32 Output 2:0x5D19F7CF

我覺得我在這里沒有理解一些東西......

  1. 如果你做對了,你就不會得到零。 你每次都得到相同的常數,但這個 CRC 不為零。 對於這個,常數是0x2144df1c (它不是零,因為有一個非零值的最終異或。)
  2. 你做的不對。 首先,您不需要也不應該 append 四個零。 只需計算消息的CRC。 其次,append CRC 的端序。 不是大端順序。 (因為這是一個向下移動的反射 CRC。)
  3. 以這種方式檢查 CRC 沒有什么意義。 只需計算消息的 CRC,然后其結果與發送的 CRC 進行比較。 這對於閱讀您的代碼的人來說更容易、更透明,並且避免了在另外四個字節上不必要地計算 CRC。 比較比對四個字節的 CRC 計算快得多。
  4. 為什么要在奇數長度的消息中添加一個額外的零?

暫無
暫無

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

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