Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...