如果您感兴趣,请介绍一些背景知识...
下一段代码是使用循环冗余校验(CRC-15)实现分组错误码生成器的尝试。这用于检测通信数据损坏。更详细的介绍是不必要的。
代码和问题
init_PEC15_Table函数是一个查找表生成器。
pec15函数接受数据输入,计算解决方案的地址,并在查找表中查找结果。
data是一个字符数组,我给它赋值为1。这将被传递给pec15。
现在,我发现,通过对cout命令重新排序,“ pec”的值(我感兴趣的输出)会更改。通过在线阅读,我了解到这可能是由于内存堆栈以一种影响结果寄存器的方式意外更改,也可能是由于对其他变量的越界操作。我的理解错了吗?
现在,我是一个初学者,这是非常令人畏惧的。我可能犯了一些我不知道的严重错误,所以请随时将代码撕成碎片。另外,如果重要的话,这段代码运行在一个mbed LPC1768上。
#include <iostream>
using namespace std;
unsigned short pec15Table[256];
const unsigned int CRC15_POLY = 0x4599;
void init_PEC15_Table() // Cyclical Redundancy Check lookup table generator function
{
unsigned short rem;
for (int i = 0; i < 256; i++)
{
rem = i << 7;
for (int bit = 8; bit > 0; --bit)
{
if (rem & 0x4000)
{
rem = ((rem << 1));
rem = (rem ^ CRC15_POLY);
}
else
{
rem = ((rem << 1));
}
}
pec15Table[i] = rem & 0xFFFF;
// cout << hex << pec15Table [i] << endl;
}
}
unsigned short pec15(char* data, int lengt = 16) //Takes data as an input,
{
int rem, address;
rem = 16;//PEC seed (intial PEC value)
for (int i = 0; i < lengt; i++)
{
address = ((rem >> 7) ^ data[i]) & 0xff;//calculate PEC table address
rem = (rem << 8) ^ pec15Table[address];
}
return (rem * 2);//The CRC15 has a 0 in the LSB so the final value must be multiplied by 2
}
int main()
{
init_PEC15_Table(); //initialise pec table
char data = (short) 0x1 ; // Write 0x1 to char array containing the data 0x1
char* dataPtr = &data; // Create a pointer to that array
unsigned short result = pec15(dataPtr); //Pass data pointer to pec calculator
cout << "data in: " << (short) *dataPtr << endl; //Print the short representation of the char data array (Outputs 1)
cout << "size of data: " << sizeof(*dataPtr) << endl; //Print the size of the char array (Outputs 1)
cout << "stuffed pec: " << result << endl; //Print the output of the pec calculation
return 0;
}
https://stackoverflow.com/questions/56692601
复制相似问题