1

给定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)or base10(11483)

我的 Matlab 函数给出base10(85)的是base2(00000000 01010101).

关于导致输出不符合预期的任何想法?

4

1 回答 1

1

你应该尝试bitsll()而不是bitshift(). 前者保证做你想做的事,而后者的行为取决于crc.

最后你还需要和 with 0xffff

于 2013-12-04T01:30:04.227 回答