Reprinted please indicate the source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html
Reprinted please indicate the source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html
#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned char a = -1;
char b = a;
printf("%d %d",a,b);
return 0;
}
// Result: 255-1
# Include <stdio. h>
Int main (int argc, char * argv [])
{
Unsigned short a =-1;
Short B =;
Printf ("% d", a, B );
Return 0;
}
// Result: 65535-1
These are two simple codes. I will take the second code as an example.
In a computer, negative numbers are stored as supplementary codes. Reprinted please indicate the source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html
In C language, the complement of constant integer-1 is 0 xFFFFFFFF. Truncates the last 16-bit FFFF value to variable a (unsigned short ). In this case, a = 0 xFFFF (a has no symbol bit, and 0xFFFF is converted to decimal 65535 ).
A then assigned 0 xFFFF to short B. In this case, B = 0 xFFFF (but note that B is signed and 0xFFFF is converted to-1 in decimal format ).
When printf ("% d", a, B); is executed, the values of a and B must be converted to the int type first:
A has no symbol, so it is converted to int type 0x0000FFFF,
B is converted to int Type 0 xFFFFFFFF.
Decimal output value 65535-1. Reprinted please indicate source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html
# Include <stdio. h>
Int main (int argc, char * argv [])
{
Unsigned int a =-1;
Int B =;
Printf ("% d", a, B );
Return 0;
}
// Result-1-1
Reprinted please indicate the source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html
The value of a in the memory is 0 xFFFFFFFF, and the value of B is 0 xFFFFFFFF, both of which are 32 bits,
When a is converted to the int type, it is 0 xFFFFFFFF, so the output is-1.
Actually, just remember two points.
1. When the unsigned type is converted to the signed type, it is directly copied to the low position, and the high position is 0. If the signed type has not enough digits, only the unsigned low position is loaded directly.
2. When the signed type is converted to the unsigned type, the complement code is copied directly to the low position, and the high position is the sign bit. If the number of unsigned digits is not enough, only the signed low position is loaded directly.
Reprinted please indicate the source http://www.cnblogs.com/stonehat/archive/2011/10/14/2212141.html