I just learned. How Bitwise operators work but when i try to use it in the c code i doesnt work.
#include <stdio.h>
int main()
{
int a = 7;
printf("%d\n", (int)~a);
return 0;
}
The expected output is 8 but it comes -8.
~0111
=
1000
I just learned. How Bitwise operators work but when i try to use it in the c code i doesnt work.
#include <stdio.h>
int main()
{
int a = 7;
printf("%d\n", (int)~a);
return 0;
}
The expected output is 8 but it comes -8.
~0111
=
1000
Assuming int is 32 bit on your machine then 7 is 0b00000000000000000000000000000111 and ~7 becomes 0b11111111111111111111111111111000 which is -8.
In addition to that (char) 0b10000000 is -128 and (char) 0b11111111 is -1.
So counting works as follows:
0b10000000 0b10000001 [...] 0b11111111 0b00000000 [...] 0b01111111
-128 -127 [...] -1 0 [...] 127
That is the reason why you will get -128 when you count 127+1 and try to store that in a char.