我正在研究字节顺序。我的小端程序可以运行,并提供正确的输出。但是我无法绕过大端。以下是我到目前为止所拥有的。 我知道我必须使用位移位,但我认为我在这方面做得不好。我试着问过我的助教和教授,但他们帮不上什么忙。 我一直在关注此链接 ( convert big endian to little endian in C [without using provided 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;
}
最佳答案
我回答不是给你答案而是帮你自己解决。
首先问问自己:一个字节有多少位? (提示:8)接下来,int
中有多少字节? (提示:可能是 4 个)想象一下内存中的这个 32 位整数:
+--------+
0x|12345678|
+--------+
现在在小端机器上按字节想象它。它看起来像这样:
+--+--+--+--+
0x|78|56|34|12|
+--+--+--+--+
需要哪些移位操作才能将字节放入正确的位置?
请记住,当您使用像 >>
这样的按位运算符时,您是在位上进行操作。所以 1 << 24
将是整数值 1
转换为处理器的相反字节顺序。
关于使用 Bitshift 运算符将小端转换为大端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650208/