gpt4 book ai didi

c - memcpy 混淆了结构的内容?

转载 作者:行者123 更新时间:2023-11-30 18:15:47 25 4
gpt4 key购买 nike

我一直在编写 R2K 对象模块,但在将符号表条目写入文件时遇到了问题。我一直在尝试使用 memcpy 将存储在 sym_table 中的符号表条目放入名为 bytes_sym 的一字节整数数组中,然后将其写入文件。它复制了正确的大小,但由于某种原因弄乱了字节的位置。这是我的代码:

/*
** symbol table entry
*/
typedef
struct syment {
uint32_t flags; /* flag word */
uint32_t value; /* value associated with this symbol */
uint32_t sym; /* symbol name's index into string table */
}
syment_t;

// header->data[8] is the number of symbol table entries
int sym_length = header->data[8] * sizeof(syment_t);

uint8_t bytes_sym[sym_length];

for(int i = 0; i < header->data[8]; i++){
memcpy(&bytes_sym[i * sizeof(syment_t)], &sym_table[i], sizeof(syment_t));
}
fwrite(bytes_sym, sym_length, 1, file);

// prints the newly copied symbol table section one byte at a time
// I know it's gross to look at, but it's only for testing :p
printf("New Symtab:\n");
for(int i = 0; i < sym_length; i++){
printf("0x%x ", bytes_sym[i]);
}
printf("\n");

写入之前,字节值为:

0x0 0x0 0x0 0xb1 0x0 0x40 0x0 0x2c 0x0 0x0 0x0 0x0
0x0 0x0 0x0 0xa3 0x10 0x0 0x0 0x20 0x0 0x0 0x0 0x5
0x0 0x0 0x40 0xb1 0x0 0x40 0x0 0x38 0x0 0x0 0x0 0xb
0x0 0x0 0x0 0xa1 0x0 0x40 0x0 0x14 0x0 0x0 0x0 0x10
0x0 0x0 0x40 0xb1 0x0 0x40 0x0 0x0 0x0 0x0 0x0 0x15
0x0 0x0 0x0 0x67 0x0 0x0 0x0 0x11 0x0 0x0 0x0 0x1f
0x0 0x0 0x0 0xa2 0x10 0x0 0x0 0x0 0x0 0x0 0x0 0x19
0x0 0x0 0x40 0xb1 0x0 0x40 0x0 0x64 0x0 0x0 0x0 0x29

写完后,它们是(不正确,不应该不同):

0xb1 0x0 0x0 0x0 0x2c 0x0 0x40 0x0 0x0 0x0 0x0 0x0 
0xa3 0x0 0x0 0x0 0x20 0x0 0x0 0x10 0x5 0x0 0x0 0x0
0xb1 0x40 0x0 0x0 0x38 0x0 0x40 0x0 0xb 0x0 0x0 0x0
0xa1 0x0 0x0 0x0 0x14 0x0 0x40 0x0 0x10 0x0 0x0 0x0
0xb1 0x40 0x0 0x0 0x0 0x0 0x40 0x0 0x15 0x0 0x0 0x0
0x67 0x0 0x0 0x0 0x11 0x0 0x0 0x0 0x1f 0x0 0x0 0x0
0xa2 0x0 0x0 0x0 0x0 0x0 0x0 0x10 0x19 0x0 0x0 0x0
0xb1 0x40 0x0 0x0 0x64 0x0 0x40 0x0 0x29 0x0 0x0 0x0

我无法理解造成这种情况的原因,因此我们将不胜感激!

最佳答案

好吧,你们完全撒谎说 memcpy 没有弄乱我的数据。经过一些研究后,我发现这是一个字节序的事情,它颠倒了我的 32 位对象模块的符号表部分中每个 4 字节 block 中的字节顺序。所以我写了一个小函数来修复它:

///    Flips the bytes in each 4 byte block after the endian flip caused by memcpy
/// @param - the array of bytes
/// @param - the length of the array in bytes
///
void flip_bytes(uint8_t byte_array[], int length){

uint8_t tmp;
for(int i = 0; i < length; i++){
if((i+1) % 4 == 0){

// switch the first and last bytes
tmp = byte_array[i];
byte_array[i] = byte_array[i-3];
byte_array[i-3] = tmp;
// switch the middle 2 bytes
tmp = byte_array[i-1];
byte_array[i-1] = byte_array[i-2];
byte_array[i-2] = tmp;
}
}
}

关于c - memcpy 混淆了结构的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43787951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com