无法将十六进制值传递给函数 我正在尝试将十六进制值发送到 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/