Use of -1 in bit mask portable?

Hi. I'm new to programming so please forgive me if this is an obvious question. I couldn't find a useful answer with Google.

Do all modern computers record signed numbers in such a way that -1 is always recorded as [all bits being true] or not? (For a char a byte long, -1decimal = 11111111 ?)

I saw this example (used to return the smaller value out of x and y):

r = y + ((x - y) & -(x < y));

and wondered whether it would work on all systems.

On the computer for which the code was written,

  If x<y,
    then -(x<y) is -1 which is represented as "all 1", so (x - y) & -(x < y) = x - y so r = y + x - y = x
  else
    then -(x<y) is 0 so (x - y) & -(x < y) is "all 0" so (x - y) & -(x < y) = 0 so r = y - 0.

but I understand that there are different ways of representing signed binary numbers within a computer, so -1 might not be represented as "all 1" and so wouldn't work (and -(0) might be -0). So do all modern computers use the same system or not and therefore is this code completely portable?
Do all modern computers record signed numbers in such a way that -1 is always recorded as [all bits being true] or not?
No. And it's called "two's complement".
IIRC, C and C++ are both defined over two's complement --

hmm... a quick google search shows that I am not quite correct.

Here's a paper on the issues:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2631.html

In any case, you are typically safe assuming two's complement, but if you want your code to port to anything weird, then don't assume anything about the encoding of an integer.

(For an interesting aside, check out the GCC's definition of std::string::npos.)
That's funny. You were the one who told me that it wasn't the case when I asked this question some time ago.

As for std::string::npos, well, -1 in one's complement is only ~0-1, so it's still a pretty good number. It's better than adding conditional compilation, IMO.
Interesting. Thank you.
Yes, there is a lot of hardware, some modern, that doesn't use two's complement.

That said, for the stuff OP's likely to encounter right now, it is pretty safe to assume it. When you start working on systems that are not two's complement, you really can't begin without knowing that.

Alas, sorry for the confusion. (When it comes to playing bit-arithmetic with signed numbers, I tend avoid it altogether -- since there is no easy way to satisfy all possiblities then I just code to what my primary targets are. Changes can always be made when porting to foreign systems.)
Topic archived. No new replies allowed.