gpt4 book ai didi

c - 害怕 solaris 和 linux 下的结构差异

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:34 26 4
gpt4 key购买 nike

我正在使用 fread 读取文件的第一个字节:

fread(&example_struct, sizeof(example_struct), 1, fp_input);

在 linux 和 solaris 下哪个结果不同? example_struct (Elf32_Ehdr) 是 elf.h 中定义的 Standart GNU C Liborary 的一部分吗?我很想知道为什么会这样?

一般结构如下所示:

typedef struct
{
unsigned char e_ident[LENGTH];
TYPE_Half e_type;
} example_struct;

调试代码:

for(i=0;paul<sizeof(example_struct);i++){
printf("example_struct->e_ident[%i]:(%x) \n",i,example_struct.e_ident[i]);
}
printf("example_struct->e_type: (%x) \n",example_struct.e_type);
printf("example_struct->e_machine: (%x) \n",example_struct.e_machine);

Solaris 输出:

Elf32_Ehead->e_ident[0]: (7f) 
Elf32_Ehead->e_ident[1]: (45)
...
Elf32_Ehead->e_ident[16]: (2)
Elf32_Ehead->e_ident[17]: (0)
...
Elf32_Ehead->e_type: (200)
Elf32_Ehead->e_machine: (6900)

Linux 输出:

Elf32_Ehead->e_ident[0]: (7f) 
Elf32_Ehead->e_ident[1]: (45)
...
Elf32_Ehead->e_ident[16]: (2)
Elf32_Ehead->e_ident[17]: (0)
...
Elf32_Ehead->e_type: (2)
Elf32_Ehead->e_machine: (69)

可能类似于:http://forums.devarticles.com/c-c-help-52/file-io-linux-and-solaris-108308.html

最佳答案

您没有提到机器中的 CPU,可能是 Solaris 机器中的 Sparc64 和 Linux 机器中的 x86_64,但我猜您遇到了字节顺序问题。 Intel、ARM 和当今大多数其他常见架构都是所谓的小端,Sparc 架构是大端

假设我们在 CPU 寄存器中有值 0x1234,我们想将它存储在内存中(或硬盘驱动器,无论存储在何处)。设 N 为我们要写入的内存地址。我们需要将这个 16 位整数作为两个字节存储在内存中,这里是令人困惑的部分:

使用big-endian机器将在地址N存储0x12,在地址N+1存储0x34 .小端机器将在地址N 处存储0x34,在地址N+1 处存储0x12。如果我们使用小端机器存储一个值并使用大端机器读回它,我们将交换两个字节,您将遇到您所看到的问题。

关于c - 害怕 solaris 和 linux 下的结构差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290712/

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