kelvin wu
kelvin wu

Reputation: 23

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. 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.

Upvotes: 2

Views: 157

Answers (2)

Lidong Guo
Lidong Guo

Reputation: 2857

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


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

//means :

  1. *b asking the value b pointer to (F7)

  2. %08x is asking for hex, when printing a char as an integer type it is widened to an int before printing. (FFFFFF7 now)

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100738

Since your system is small-endian, a is stored in memory as F7 FF FF FF.

b points to the first byte of a. (F7)

*b evaluates to a char. (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.

Upvotes: 4

Related Questions