I am new to C so I got confused with this code. I wanted to know how one's complement will work for integer variable
Code:
int f = 45;
printf("Value of %d is = %d",f,~f);
now output is coming as
"Value of 45 is = -46"
My question is: this is integer variable and in my compiler int is of 4 bytes i.e. 2^32
so that means it will be represented in machine as
4294967296 . . . . . . . 32 16 8 4 2 1
0 1 0 1 1 0 1
right? or it will be represented till first 8 bits?
If represented till 32 bits then number between '32' bit and '4294967296' will be 0 right because this is 4 bytes integer and this needs to be represented this way right?
What about representation of number, I need some reference point then. I will research on my own, Assume int is of 4 bytes, if I write int a = 3; will it be represented with 8-bits representation 00000011 or with 00000000000000000000000000000011 and if I write int a = 257, will it be represented with 0000000100000001 or with 00000000000000000000000100000001 Please give me some hint or explanation on this?
Then when we're going to calculate ~ 1s complement, we're going to invert the values of bit, thus in this case bits between 32 and 4294967296 will be turned to 1 from 0 ? If so, then it's going to become some big value? How was this -46 calculated here?


As you say,
~fresults in the "one's complement" value off, i.e. looking at the binary representation,~fwill flip all bits off. Hence,~is usually referred to as the "bitwise NOT" operator. On a system whereintis 32 bits, all values of that type are represented using the full 32 bits, regardless of the value. Hence, e.g. "3" is represented as00000000 00000000 00000000 00000011and thus "~3" is11111111 11111111 11111111 11111100.Your computer, like most modern computers does not use "one's complement" for representing negative integers. It uses "two's complement" instead. Thus, when printing the value of
~fit will print the value which the bit pattern of~frepresents in "two's complement", not "one's complement".The rule is quite simple. If
fis a positive integer, then in "two's complement":or, equivalently:
Thus in this case, where
f= 45, we get~f= -(45+1) = -46.