【发布时间】:2017-05-04 16:09:47
【问题描述】:
我一直在编写 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
我无法理解是什么原因造成的,因此我们将不胜感激!
【问题讨论】:
-
欢迎来到 Stack Overflow。请尽快阅读About 和How to Ask 页面。数据结构是什么样的?我们需要知道这一点。另请阅读有关如何创建 MCVE (minimal reproducible example) 的信息。
-
所以你也想看看代码写入和读取数据吗?同时将
0x%x设为0x%02x。 -
看起来像是一个大端与小端的问题。我们需要更多信息,尤其是minimal reproducible example 会有所帮助,但
memcpy绝对不会混淆任何东西。问题出在其他地方。 -
我的理解是正确复制了值。正是您阅读它们以打印的方式是导致问题的原因。你能在 memcopy 之前显示打印代码吗?还有哪一个是正确的?
-
您实际上需要提供minimal reproducible example 才能确定查看,但似乎更有可能是您没有一致地打印数据。跨度>