指针类型转换问题 (C)

huangapple go评论52阅读模式
英文:

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 &lt;stdio.h&gt;


int main() {

    unsigned int block = 0;
    unsigned int alp = 0;

    char *input =&quot;test&quot;;

    unsigned int *pt = NULL;

    pt = (unsigned int*)input;


    alp |= ((*pt) &gt;&gt; 8);
    printf(&quot;pointer value:\t %d \n&quot;, alp);


    for(int a = 0; a &lt; 3; a++) {
        block |= (unsigned char)input[a];
        if(a != 2) {
            block &lt;&lt;= 8;
        }
    }
    printf(&quot;block value:\t %d \n&quot;, 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] &lt;&lt; 16) | (input[1] &lt;&lt; 8) | (input[2]);

If you're on a little-endian system(which most people are), then the value of alp is

(input[3] &lt;&lt; 16) | (input[2] &lt;&lt; 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.

More info on endianness

huangapple
  • 本文由 发表于 2023年1月9日 04:10:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定