使用Bitshift运算符将little endian转换为big endian

Man*_*ani 1 c

我正在研究endianess.我的小端程序工作,并给出正确的输出.但我无法绕过大端.以下是我到目前为止所拥有的内容.我知道我必须使用位移,我不认为我做得很好.我试过询问我的TA和教授,但他们帮助不大.我一直在关注这个链接(在C中将big endian转换为little endian [不使用提供的func])以了解更多但仍然无法使其工作.感谢您的帮助.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE* input;
    FILE* output;

    input = fopen(argv[1],"r");
    output = fopen(argv[2],"w");
    int value,value2;
    int i;
    int zipcode, population;
    while(fscanf(input,"%d %d\n",&zipcode, &population)!= EOF)
    {
        for(i = 0; i<4; i++)
        {
        population = ((population >> 4)|(population << 4));
        }
        fwrite(&population, sizeof(int), 1, output);
    }

    fclose(input);      
    fclose(output);

    return 0;
}   
Run Code Online (Sandbox Code Playgroud)

mpo*_*llo 7

我回答的不是给你答案,而是帮你自己解决.

首先问问自己:一个字节中有多少位?(提示:8)接下来,一个字节是int多少?(提示:可能是4)在内存中描绘这个32位整数:

  +--------+
0x|12345678|
  +--------+
Run Code Online (Sandbox Code Playgroud)

现在用字节方式将它映射到一个小端机器上.它看起来像这样:

  +--+--+--+--+
0x|78|56|34|12|
  +--+--+--+--+
Run Code Online (Sandbox Code Playgroud)

将字节输入正确的位置需要哪些移位操作?

请记住,当您使用按位运算符时>>,您正在操作.那么1 << 24将整数值1转换为处理器的相反字节序.