Reputation: 23
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
Reputation: 2857
+-----------------------+
| F7 <--b=(char *) &a|
| FF |
| FF |
| FF |
| |
+-----------------------+
printf("%08x",*b);
//means :
*b
asking the value b pointer to (F7)
%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
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