CRC16 (Modbus) 计算----无法将十六进制值传递给函数

标签 c

无法将十六进制值传递给函数 我正在尝试将十六进制值发送到 crc16_2()。它没有显示任何错误,但我没有得到输出。 请转到代码的最后一行,以输出 abc[] 数组中的十六进制值数据。

#include<stdio.h>
#include<conio.h>
unsigned int CRC16_2(unsigned int *buf, int len)
{
    unsigned int crc = 0xFFFF;
    for (int pos = 0; pos < len; pos++)
    {
        crc ^= (unsigned int)buf[pos];  // XOR byte into least sig. byte of crc
        for (int i = 8; i != 0; i--)
        {    // Loop over each bit
            if ((crc & 0x0001) != 0)
            {      // If the LSB is set
            crc >>= 1;                  // Shift right and XOR 0xA001
            crc ^= 0xA001;
            }
            else                        // Else LSB is not set
            crc >>= 1;                  // Just shift right
        }
    }
    return crc;
}
int main()
{
    unsigned int abc[5]={0x020300000001,0x020300010001,0x020300020001,0x020300030001,0x020300040001};
    unsigned int final;
    for(int i=0;i<5;i++)
    {
        final=CRC16_2(abc[i],12);
        printf("%.4x\n",final);
    }
}
//outputs are : 3984, F9D5, F925, 3974, F8C5

最佳答案

正如普拉斯所说:

Use long long instead of int, 0x020300000001 wont fit in 4 byte int, first confirm int size with sizeof int

此外,您还将数组的 1 个元素传递给函数,因此它只是一个整数。 (即被剪切到最后 4 个字节)。

该函数接受一个指向整数的指针,但您给它一个整数。据我们所知,内存没有为您的程序分配,因此一旦您取消引用它,这就是未定义的行为。

您还可以访问整数指针,但只处理 2 个字节。这看起来很奇怪。

因此,要么您不向我们展示完整的代码,要么您可以将代码更改为类似的内容:

pass the variable

split it into 2 byte parts and save it into an array. Then you can use your double for loop to process it.

if you already want to pass the array you have to split it correctly (2 byte chunks) before hand and then pass it correctly

并且通常使用可以包含要保存的变量的数据类型。

关于CRC16 (Modbus) 计算----无法将十六进制值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49623934/

相关文章:

c - 为什么除非复制,否则指向 malloc 区域的指针会失败?

c - 在 Perl 中实现类似 sscanf 的功能的最佳方法是什么?

c - 测量线程的上下文切换时间

c - 麻烦制作一个计算器,它可以告诉我 C 中两个数字的商的分数和小数形式

c - 在结构指针中引用结构指针

c - 为什么结构成员似乎有一个溢出值?

我可以将整数分配给字符指针数组吗?

c - 无法让 Unix FIFO 正常工作?

C:通过 void 指针然后强制转换实现平台独立性

c - gtk_label_set_markup 中的变量