Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

But but but, this doesn't answer the question!? It explicitly acknowledges that -1 will not always set all bits to one, yet it recommends it!

That makes me very surprised by (1) the number of up-votes, and (2) the green "check" mark of approval.



But but but, you apparently didn't understand the answer. It doesn't matter what the representation of -1 is. The C standard defines the cast of a negative number to an unsigned int as the (UINT_MAX + 1) modulo of the number. By definition,

  unsigned int foo = -1;
will set foo to 0xFFFF..., automatically setting all bits to 1 regardless of the number of bits in int types and without respect to the representation of negative numbers.


EDIT : OK, just got it: I got the logic backwards: first, -1 is converted to uint. Second, -1 uint means UINT_MAX. Third, the binary representation of UINT_MAX is all 1s. The way I previously understood it, the -1 would be a signed integer which has some binary representation, and that binary representation would become the uint.

Weird bit of arcana. Below is my mistaken comment. (Notice that I pretended that UINT_MAX is not all 1s, which is silly. I suppose I made that mistake because I "couldn't be wrong" or something.)

As far as I know, your definition can't be inferred from the C standard. The answer itself acknowledges that -1 doesn't yield 0xFFFF… on every platform. The only guarantee is that it will yield UINT_MAX, which is not what was asked.

Otherwise, that would mean that C basically mandates a two's complement representation. Does it?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: