Let me try to explain what is happening...
Here's code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int var1 = 5;
char tmp;
tmp = ~(char)var1;
unsigned int var2 = tmp;
printf("\nvar1 = %u, var2 = %u, tmp = %d",var1,var2,tmp);
system("pause");
}
My output:
var 1 = 5, var2= 4294967290, tmp = -6
Why?
OK, on most machines (32 bit) unsigned it is 4 bytes (you can check with sizeof operator) and number 5 is represented like:
00000000 00000000 00000000 00000101
now when you cast it to char (1 byte) you get:
00000101
Now when you complement it you get
11111010
Since you tmp is defined as signed (default signed on most compilers) this is interpreted in this way:
first bit is signed bit if it is 1 tthen nubmer is negative,since it's two's complement number is then
1111010 this must be complemented first
0000101
and 1 is added so finaly
Code:
0000101
+0000001
-------------
0000110
So number is -6.
Now, in line:
Code:
unsigned int var2 = tmp;
you there is a promotion form char to unsigned int.
Since tmp is interprated as negative number because the most significat bit is 1 it will be promoted like:
11111111 11111111 11111111 11111010
and that is var2= 4294967290.
So, basically your question is about char to int promotion. I strongly recommend you reading FAQ. If you want to get result 250 you'll need to use something like this:
Code:
unsigned int var2 = (unsigned char)(~(char)var1);
Hope this helps.
- Micko