【问题标题】:16-bit CRC-CCITT in MatlabMatlab 中的 16 位 CRC-CCITT
【发布时间】:2013-12-20 07:24:46
【问题描述】:

给定下图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)

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

【问题讨论】:

  • 您是否尝试过一次一行地遍历它们并比较每行的输出以查看它们开始偏离的位置?

标签: matlab crc16


【解决方案1】:

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

您还需要在末尾加上0xffff

【讨论】:

  • 关于bitshift 的有用警告,当输入为负数时将拉入 1 秒。 +1
猜你喜欢
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 2011-07-05
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多