簡體   English   中英

Matlab中的16位CRC-CCITT

[英]16-bit CRC-CCITT in Matlab

給定如下所示的calcCRC() C函數,等效的Matlab函數是什么?

C語言中的16位CRC-CCITT:

/*
 * FUNCTION: calcCRC calculates a 2-byte CRC on serial data using
 * CRC-CCITT 16-bit standard maintained by the ITU
 * ARGUMENTS: queue_ptr is pointer to queue holding are a to be CRCed
 * queue_size is offset into buffer where to stop CRC calculation
 * RETURNS: 2-byte CRC
 */
unsigned short calcCRC(QUEUE_TYPE *queue_ptr, unsigned int queue_size) {
    unsigned int i=0, j=0;
    unsigned short crc=0x1D0F; //non-augmented initial value equivalent to augmented initial value 0xFFFF

    for (i=0; i<queue_size; i+=1) {
        crc ^= peekByte(queue_ptr, i) << 8;

        for(j=0;j<8;j+=1) {
            if(crc & 0x8000) crc = (crc << 1) ^ 0x1021;
            else crc = crc << 1;
        }
    }

    return crc;
}

下面是我想出的Matlab代碼,這似乎是等效的,但不會輸出相同的結果:

(錯誤)Matlab中的16位CRC-CCITT:

function crc_val = crc_ccitt_matlab (message)
    crc = uint16(hex2dec('1D0F'));

    for i = 1:length(message)
        crc = bitxor(crc,bitshift(message(i),8));

        for j = 1:8
            if (bitand(crc, hex2dec('8000')) > 0)
                crc = bitxor(bitshift(crc, 1), hex2dec('1021'));
            else
                crc = bitshift(crc, 1);
            end
        end
    end

    crc_val = crc;
end

這是一個示例字節數組,表示為整數數組:

78 48 32 0 251 0 215 166 201 0 1 255 252 0 1 2 166 255 118 255 19 0 0 0 0 0 0 0 0 0 0 0 0 3 0

預期的輸出是兩個字節base10(44 219) ,即base2(00101100 11011011)base10(11483)

我的Matlab函數給出的base10(85)base2(00000000 01010101)

關於什么導致輸出不符合預期的任何想法?

您應該嘗試使用bitsll()而不是bitsll() bitshift() 保證前者可以做您想要的事情,而后者的行為取決於crc屬性。

您還需要以0xffff結尾。

暫無
暫無

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

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