简体   繁体   English

如何正确地从内存中读取数据(memcpy)

[英]How to properly read data from memory (memcpy)

I have some tables, for example one declared as uint8_t keyLock[16]; 我有一些表,例如一个表声明为uint8_t keyLock[16]; , and I have saved contents of these tables in the flash memory of my MCU. ,并将这些表的内容保存在MCU的闪存中。 In this memory its looks like below: 在此内存中,其外观如下所示:

Address    Data
00190008 - BA98B694
0019000C - E854B6E7
00190010 - 9200B2C9
00190014 - 42F8B048

When I copy the flash data into my table via the memcpy function ( memcpy(keyLock, 0x00190008, 32); ) the contents of table end up as if initialized this way: 当我通过memcpy函数( memcpy(keyLock, 0x00190008, 32); )将闪存数据复制到表中时,表的内容最终以这种方式初始化:

keyLock = {
    0xBA, 0x98, 0xB6, 0x94, 0xE8, 0x54, 0xB6, 0xE7,
    0x92, 0x00, 0xB2, 0xC9, 0x42, 0xF8, 0xB0, 0x48
}

I want the contents to be as if the table were initialized like this: 我希望目录看起来像是这样初始化的:

keyLock = {
    0x94, 0xB6, 0x98, 0xBA, 0xE7, 0xB6, 0x54, 0xE8,
    0xC9, 0xB2, 0x00, 0x92, 0x48, 0xB0, 0xF8, 0x42
}

What is wrong with my memcpy() call, and how should I write it to fill the table with the desired content, as above? 我的memcpy()调用有什么问题,如何如上所述将其编写为用所需的内容填充表?

When you store 4 bytes of memory as a 32 but integer whose value is BA98B694 , which byte goes first? 当您将4个字节的内存存储为32个但值为BA98B694整数时,哪个字节BA98B694

In your question, you implicitly assume the BA byte goes first, but on your system it appears that 94 goes first. 在您的问题中,您隐式地假设BA字节排在最前面,但是在您的系统上, 94似乎在最前面。

Your memcpy is doing everything right. 您的memcpy所做的一切正确。 Your problem is your expectation of endianness, or the layout of your table in flash. 您的问题是您对字节顺序的期望,或是Flash中表格的布局。

You can fix it by simply swapping the order of each 4 byte dword. 您可以通过简单地交换每个4字节dword的顺序来修复它。

void endian_4byte_swap( uint32_t* bytes ){
  std::swap(bytes[0],bytes[3]);
  std::swap(bytes[1],bytes[2]);
}
void endian_fix_table( uint32_t (&table)[16] ){
  for(int i=0;i<4;++i)
    endian_4byte_swap(&table[4*i]);
}

But that fixes the symptom rather than the disease. 但这可以解决症状而不是疾病。 The real fix is to fix the table in flash, assuming you have control over it. 真正的解决方法是假设您可以控制表格,将其固定在闪存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM