Jonny Iversen said:
Following 1111 (or hexadecimal 0xF) bits is actually -1 as an result from
VC++.
But ~ is one complement operator which should give the answer:
1110 which is the one complement for -1. So when is this further converted
to the
two complements form aka 1111 or 0xF?
I don't really understand that ~0 can give -1 as the answer when ~ is said
to be one complement operator the answer should have been 1111 that's -0
in
one complement.
First of all, is it clear what the operator ~ actually does? Taken a
sequence of bits, it converts any 0 to 1 and any 1 to 0. Full stop.
Everything else is just an interpretation of the binary sequences.
When I say 'interpretation', I mean that the same sequence of bits can have
various meanings, depending on your application. For somebody, the value
1111...1111 (all 1's) is -1, for other it may be e.g. 255 (suppose there are
eight 1's), some can interpret it as -0 (as you noticed), for yet other
people it is a Unicode code for a letter y with two dots at top of it, in MS
DOS world it represents a character which looks as a space (but is not a
space) etc.
What does happen in your case? Well, you have a conflict between two
*interpretations* for integers - "one's complement" and "two's complement".
You have a value 0000...0000, which origins from the integer 0 - in any of
these two interpretations. Then you apply operator ~ and you get
1111....1111. The result now has different interpretations: in "one's
complement" it is -0, in "two's complement" it is -1.
What actually happens is that your compiler uses the two's complement
interpretation to convert integers to binary sequences and vice versa. You
just haven't noticed the first conversion (0 -> 0000...0000), but you have
noticed the second one (1111...1111 -> -1). This interpretation is inbuilt
into the compiler.
In other words: the operator ~ just flips bits. It knows nothing about any
interpretation. It even has nothing with the "one's complement"
interpretation. What confuses you is actually the VC++ documentation,
because it mentions something like "one's complement". There are disputable
didactical reasons why this is so... perhaps the operator ~ "looks like"
operator - (minus) in the world where all integers are represented by "one's
complement" interpretation. And really, if your compiler used one's
complement, then the operator ~ would work just the same as operator -, and
you would not have a reason for its existence (it would be a duplicate).
But, alas, your compiler doesn't use the "one's complement interpretation"
(actually, it is bound by C++ standard to use "two's complement").
Note 1: Personally, I would never mention "one's complement" in an
explanation of the operator ~. Usually a definition is a reduction of
unknown to a known, not the reduction of unknown to something even less
known!
Note 2: When I say "compiler", I mean, actually, "the resulting program
generated by your compiler".
I hope this will be of help to you.
Regards,
Rade