我试图从微控制器获取一些数据包到 C# 程序:
我在两个地方都定义了一个结构。我计算 (sizeof(packet)-4bytes) 的 crc32 并将其放在 mydata_t.crc32 ...
struct mydata_t
{
public byte cmd;
public UInt32 param;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public Char[] str_buf;
public UInt32 crc32;
}
private byte[] getBytes(mydata_t str)
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
private mydata_t fromBytes(byte[] arr)
{
mydata_t str = new mydata_t();
str.str_buf = new char[10];
int size = Marshal.SizeOf(str);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
str = (mydata_t)Marshal.PtrToStructure(ptr, str.GetType());
Marshal.FreeHGlobal(ptr);
return str;
}
public static UInt32 xcrc32(byte[] buf, int len)
{
UInt32 crc = DefaultSeed;
UInt32 counter = 0;
while (len-- > 0)
{
crc = (crc << 8) ^ defaultTable[((crc >> 24) ^ buf[counter]) & 255];
counter++;
}
return crc;
}
我的 CRC 函数需要字节和长度..所以当我收到数据时..“以字节为单位”我使用 ( private mydata_t fromBytes(byte[] arr)
)将它们转换为结构
问题: 当我从结构转换为字节数组时,计算 CRC 是错误的“我相信这是因为 c# 中数据类型的字节顺序?我该如何解决这个问题?
这是我从微控制器发送的:
mydata_t datablockTX;
datablockTX.cmd = 2;
datablockTX.param = 0x98765432;
memcpy(datablockTX.str_buf,"hellohell",10);
datablockTX.crc32 = xcrc32((char*) &datablockTX,sizeof(datablockTX) - sizeof(uint32_t));
usb_write_buf((uint8_t*) &datablockTX,sizeof(datablockTX));
这是我收到并打印的:
Data Received:
CMD: 2
param: 2557891634
str: hellohell
crc: 658480750
然后是问题:
public bool ValidateCRC()
{
bool myvalidate;
UInt32 mycrc_val;
byte[] mybytes = getBytes(myblock);
mycrc_val = Crc32.Crc32Algorithm.xcrc32(mybytes, mybytes.Length- sizeof(UInt32));
//mycrc_val = Crc32.Crc32Algorithm.xcrc32(mybytes, 1);
myvalidate = (mycrc_val == myblock.crc32);
Console.WriteLine("c#:" + mycrc_val + " - MCU:" + myblock.crc32 + " - bool:" + myvalidate);
return myvalidate;
}
这是它在控制台中打印的内容: c#:667986744 - SAM:658480750 - bool:False
我在MCU中试过这个:
mydata_t datablockTX;
datablockTX.cmd = 2;
datablockTX.param = 0x98765432;
memcpy(datablockTX.str_buf,"hellohello",10);
//datablockTX.crc32 = xcrc32((char*) &datablockTX,sizeof(datablockTX) - sizeof(uint32_t));
datablockTX.crc32 = xcrc32((char*) &datablockTX, 5);
usb_write_buf((uint8_t*) &datablockTX,sizeof(datablockTX));
这是我收到的:
指令:2
参数:2557891634
str:你好你好
CRC: 1993296691
在 C# 中:
byte[] mybytes = getBytes(myblock);
//mycrc_val = Crc32.Crc32Algorithm.xcrc32(mybytes, mybytes.Length- sizeof(UInt32));
mycrc_val = Crc32.Crc32Algorithm.xcrc32(mybytes, 5);
myvalidate = (mycrc_val == myblock.crc32);
Console.WriteLine("c#:" + mycrc_val + " - MCU:" + myblock.crc32 + " - bool:" + myvalidate);
控制台:c#:146416248 - MCU:1993296691 - bool:False