Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do unsigned int x = -1 and int y = ~0 have the same binary representation?

Tags:

c

binary

In the following code segment what will be:

  • the result of function
  • value of x
  • value of y
    {
         unsigned int x=-1;
         int y;
         y = ~0;
         if(x == y)
             printf("same");
         else
             printf("not same");
     }
a. same, MAXINT, -1
b. not same, MAXINT, -MAXINT
c. same , MAXUINT, -1
d. same, MAXUINT, MAXUINT
e. not same, MAXINT, MAXUINT

Can someone explain me how its works or can just explain the snippet??

I know it's about two's complement n etc.. What is the significance of MAXINT and -1 ? It is because of unsigned int and int thing - am I right ?

like image 245
shraddha Avatar asked Jun 29 '10 13:06

shraddha


2 Answers

unsigned int x=-1;

1 is an integer literal and has type int (because it fits in an int). Unary - applied to an int causes no further promotion so -1 is an int with value -1.

When converted to an unsigned int modulo 2^N arithmetic is used where N is the number of value bits in an unsigned int. x has the value 2^N - 1 which is UINT_MAX (What's MAX_UNIT?).

int y;
y = ~0;

Again 0 is type int, in C all the allowed representations of int must have all the value bits of an int representing 0 as 0. Again no promotion happens for unary ~ so ~0 is an int with all value bits being 1. What it's value is is implementation dependent but it is negative (the sign bit will be set) so definitely neither of UINT_MAX or INT_MAX. This value is stored in y unchanged.

if(x == y)
    printf("same");
else
    printf("not same");

In this comparison y will be converted to unsigned int in order to be compared with x which is already an unsigned int. As y has an implementation value, the value after conversion to unsigned int is still implementation defined (although the conversion itself is modulo 2^N and fully specified). The result of the comparison is still implementation defined.

So in conclusion:

implementation defined, UINT_MAX, implementation defined

In practice on ones' complement:

not same, UINT_MAX, -0 (aka 0)

sign plus magnitude:

not same, UINT_MAX, INT_MIN

two's complement:

same, UINT_MAX, -1

like image 52
CB Bailey Avatar answered Sep 21 '22 11:09

CB Bailey


Its pretty easy. The twos complement representation of -1 is 0xFFFFFFFF. Hence that is what x contains.

The complement operator (~) flips all the bits. So the complement of 0 is a 32-bit number with all the bits set to 1 or 0xFFFFFFFF.

Edit: As pointed out int he comments. The answer is not A. If it was then it would be saying 0x7FFFFFFF and 0xFFFFFFFF are the same. They're not. The real answer is C (Assuming MAXUNIT is a typo ;)).

like image 35
Goz Avatar answered Sep 19 '22 11:09

Goz