@nrailgun
2015-10-01T14:38:22.000000Z
字数 1392
阅读 1436
程序设计
C is a low level language, which processes memory (variable) directly. When you are working with hardware or network / transmission protocol, you have to deal with signed or unsigned bytes, integers often.
It's usual to perform calculation on different size integers or different signedness integers. Problems happen here. Misunderstanding of C type casting keeps making troubles.
When arithmetic operations are performed on 2 different type operands, integeral promotions are performed first. Integeral promotions converts integer type smaller than int
or unsigned int
to int
or unsigned int
. If operands still have different type, following conversions will be performed.
What will happen I decide to assign a value out of range to a variable? If the variable is unsigned, wrap around will happen. Only lower bits will be kept (C++ Primer says C++ keeps modules. I think it is the same).
If the variable is signed, it's compiler dependent. But usually the same as unsigned. I tested on Linux with gcc, and it turn out to be the same. C and C++ simply strip higher part off.
By the way, what shocked me(Jesus christ! I thought it was for certain!):
Selecting the MSB or LSB as signness bit is Compiler dependent.
#include <stdio.h>
int main(void)
{
unsigned char a = 0xff;
char b = 0xff;
int c = a == b; // true or false?
printf("C: %d\n", c);
return 0;
}
Now, you should know: a == b
first cast a
to unsigned int
(which is 0x000000ff
), and b
to int
(which is 0xffffffff
), then cast both to unsigned int
. Of course, a == b
is false
.