Reputation: 23
I wanted to test what happens when I write this code. I can not explain the following case:
Input: 5 Output: -6
#include <iostream>
int lastBit(int n){ return ~(n); }
int main() { std::cout << lastBit(5); }
Upvotes: 0
Views: 133
Reputation: 23
I found out the following
5 = 0101 Therefore, ~(5) = 1010
Therefore, output is -6 Since this is a 2's complement machine
Upvotes: 0
Reputation: 25927
Computers express negative numbers in quite a specific way. Values are always stored as series of bits and there is no way of introducing negative sign, so this has to be solved differently: one of bits plays role of a negative sign.
But this is not all - the system must be designed to handle maths properly (and ideally, the same way as for positive numbers).
So for instance 0 == 0b00000000
. If you subtract 1 from 0, you get -1, but from the binary perspective, due to "binary underflow", 0b00000000 - 0b00000001 == 0b11111111
, hence 0b11111111 == -1
.
If you then subtract 1 from -1, you get 0b11111111 - 0b00000001 == 0b11111110 == -2
. But 2 == 0b00000010
, which shows, why -2 != ~2
(and the same rule applies to next values).
The very short, but maybe more intuitive answer might be: "-5 != ~5, because there is only one zero binarily (eg. 0 == -0), so there is always one more negative value than positive ones"
Upvotes: 3
Reputation: 14589
Not on all systems but on systems that use complement of two for signed values. By definition there, the binary representation of negative X = -n
, where n
is a positive integer, is ~n + 1
, which allows signed and unsigned addition operations to be same.
Until C++20 result of ~(n)
for signed negative n
here would be undefined, because it depends on platform and compiler. In C++20 it's required to behave as if complement of two is used.
Upvotes: 2