C Big Endian到Little Endian结构

时间:2014-02-11 21:57:12

标签: c struct endianness

我有一个定义为的结构:

struct record
{
   int age;
   char name[12];
   int department;
};

如果我正在从二进制文件中读取数据并且数据包含结构,我怎么能解决这个问题呢?如何在该结构中反转从big endian到little endian的位的顺序?

1 个答案:

答案 0 :(得分:0)

这是一个转换字节序的简单实现:

// Convert from big to little or vice versa
void convert_record (struct record *bigLittle) {
    int x, temp;

    temp = bigLittle->age;

    for (x = 0; x < sizeof (int); x++) {
        ((char *)&(bigLittle->age))[x] = ((char *)&temp)[sizeof (int) - x]
    }

    temp = bigLittle->department;

    for (x = 0; x < sizeof (int); x++) {
        ((char *)&(bigLittle->department))[x] = ((char *)&temp)[sizeof (int) - x]
    }

    return;
}

然而,正如Michael Foukarakis上面指出的那样,你真的应该使用ntohs和朋友。