英文:
pointer cast issue (C)
问题
也许你们中的某个人可以帮助我。我不知道该怎么办了。我有以下的测试代码:
#include <stdio.h>
int main() {
unsigned int block = 0;
unsigned int alp = 0;
char *input = "test";
unsigned int *pt = NULL;
pt = (unsigned int*)input;
alp |= ((*pt) >> 8);
printf("指针值:\t %d \n", alp);
for(int a = 0; a < 3; a++) {
block |= (unsigned char)input[a];
if(a != 2) {
block <<= 8;
}
}
printf("块值:\t %d \n", block);
return 0;
}
我期望这两个值应该完全相同,因为它们都查看了完全相同的3个字节。但是实际上这两个值有差异。是否有人知道为什么会这样,或者能解释一下为什么会这样?
指针值: 7631717
块值: 7628147
使用以下命令编译:"gcc test.c -Wall -o test"(gcc(Ubuntu 12.2.0-3ubuntu1)12.2.0)
非常感谢。
英文:
maybe one of you can help me. I don't know what to do anymore. I have the following test code:
#include <stdio.h>
int main() {
unsigned int block = 0;
unsigned int alp = 0;
char *input ="test";
unsigned int *pt = NULL;
pt = (unsigned int*)input;
alp |= ((*pt) >> 8);
printf("pointer value:\t %d \n", alp);
for(int a = 0; a < 3; a++) {
block |= (unsigned char)input[a];
if(a != 2) {
block <<= 8;
}
}
printf("block value:\t %d \n", block);
return 0;
}
I would expect both values to be exactly the same, since they look at exactly 3 bytes. Only the values have a difference. Does anyone have an idea why this is the case or can explain me why?
pointer value: 7631717
block value: 7628147
Compiled with "gcc test.c -Wall -o test" (gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0)
Many thanks
答案1
得分: 0
block 的值为
(input[0] << 16) | (input[1] << 8) | (input[2]);
如果你在一个小端系统上(大多数人都是),那么 alp 的值是
(input[3] << 16) | (input[2] << 8) | (input[1]);
没有任何可疑的情况。在小端系统上,不同的结果是预期的。您的 CPU 将第一个字节视为最不重要的字节,最后一个字节视为最重要的字节,但您的 for 循环将第一个字节视为最重要的字节,最后一个字节视为最不重要的字节。
英文:
The value of block is
(input[0] << 16) | (input[1] << 8) | (input[2]);
If you're on a little-endian system(which most people are), then the value of alp is
(input[3] << 16) | (input[2] << 8) | (input[1]);
There's nothing fishy going on. the different results are expected on a little-endian system. Your CPU reads the first byte as the least significant one and the last byte as the most significant one, but your for loop reads the first byte as the most significant one and the last byte as the least significant one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论