cones-complement

1s complement representation for integer variable in C


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?


Solution

  • As you say, ~f results in the "one's complement" value of f, i.e. looking at the binary representation, ~f will flip all bits of f. Hence, ~ is usually referred to as the "bitwise NOT" operator. On a system where int is 32 bits, all values of that type are represented using the full 32 bits, regardless of the value. Hence, e.g. "3" is represented as 00000000 00000000 00000000 00000011 and thus "~3" is 11111111 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 ~f it will print the value which the bit pattern of ~f represents in "two's complement", not "one's complement".

    The rule is quite simple. If f is a positive integer, then in "two's complement":

    -f == ~f+1
    

    or, equivalently:

    ~f == -(f+1)
    

    Thus in this case, where f = 45, we get ~f = -(45+1) = -46.