1
$\begingroup$

If you have a signed integer int x = any

And then state that x < 0

Is the following statement true or false?

((x*2) < 0)

The answer is false, which seems counter intuitive. Is it because X can be any negative value, it can also be a very big negative value which will overflow if multiplied by two.

So if I have the number -30768 1000011111010000 which multiplied by 2 is -61536 11111111111111110000111110100000

But because we only have 16 bits the last 16 are taken resulting in 0000111110100000 which is positive.

Is this the correct explanation? I can't seem to find a good source

$\endgroup$
1
$\begingroup$

This depends on the rules of your programming language, which you need to check.

For any fixed size integral type that has more than the single value zero, there are integers that can be represented in the type, for which the mathematical value 2*x cannot be represented. So something has to give.

In C and C++, a signed integer overflow is undefined behaviour, so anything can happen. In Swift, a signed integer overflow causes a guaranteed crash. Swift also has the operator &* which doesn't crash, and which produces the mathematical product, plus or minus some suitable multiple of 2^n if n bits are used (there is also &+ and &- with similar behaviour). Other languages may have other rules. For example, primitive operations can be saturating: If the mathematical result is too large / too small, the largest / smallest possible value is returned instead. For such a language, x < 0 would imply 2*x < 0.

| cite | improve this answer | |
$\endgroup$
1
$\begingroup$

Your answer is nearly right.

So x is an unsigned negative value of k bits. The smalles possible value of x is representet by the 2's Complement number 1000....0. If you multiply this number by 2 (or logical shifting it by 1, which is equivalent) you end up with the number 0000...0 which is 0. And therefore (x*2)<0 is false.

| cite | improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.