简体   繁体   English

如何解释C程序的输出

[英]How to explain this output of a C program

Code: 码:

int main()
{
    unsigned int a = 0xfffffff7;
    char *b = (char *)&a;
    printf("%08x",*b);
}

the output is: fffffff7 . 输出为: fffffff7 My machine is little-endian. 我的机器是小端的。 Of course I know *b equals 0xf7 , but I don't know why the output of printf() is like this. 当然,我知道*b等于0xf7 ,但是我不知道为什么printf()的输出是这样的。

Since your system is small-endian, a is stored in memory as F7 FF FF FF . 由于您的系统是小字节序的,因此a作为F7 FF FF FF存储在内存中。

b points to the first byte of a . b指向的第一个字节a (F7) (F7)

*b evaluates to a char . *b计算为char (F7) (F7)

*b is promoted to an int in order to pass it as a parameter, since it's of type char (which usually defaults to signed char ) it is sign-extended to become FFFFFFF7 . *b被提升为int以便将其作为参数传递,因为它的类型为char (通常默认为signed char ),因此将其符号扩展为FFFFFFF7

 +-----------------------+
 |  F7   <--b=(char *) &a|
 |  FF                   |
 |  FF                   |
 |  FF                   |
 |                       |
 +-----------------------+


 printf("%08x",*b);

//means : //表示:

  1. *b asking the value b pointer to (F7) *b要求值b指向(F7)的指针

  2. %08x is asking for hex, when printing a char as an integer type it is widened to an int before printing. %08x请求十六进制,当将char打印为整数类型时,在打印之前将其扩展为int (FFFFFF7 now) (现在为FFFFFF7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM