Reputation: 19
#include<stdio.h>
void main()
{
int a, b, c;
a=5;
b=8;
c= ~(a|b);
printf("%d",c);
}
The expected the output is -13
but the results shows -14
. How is it - 14
? .
Upvotes: 1
Views: 62
Reputation: 721
It's because of 2's complement.
Using 8 bit signed values (it works the same with 32 bit signed, but this is easier to demonstrate):
8: 00001000
5: 00000101
8 | 5: 00001101
~(8 | 5): 11110010 = 242 (unsigned)
Quick way to do 2's complement when the MSb is high is to subtract 2^n (here n is 8, 2^8 is 256)
242-256=-14
Upvotes: 0
Reputation: 1840
Let's assume you use 8-bit integers:
a=5
is represented as 00000101
b=8
is represented as 00001000
a|b
is 00001101
When you invert the bits, it will be 11110010
, which in Two's complement is -14
.
Upvotes: 0
Reputation: 223689
This is due to two's complement representation of negative numbers. Two's complement is performed by inverting all bits then adding one.
First, you have a|b
(for simplicity's sake I'll show only the low order 8 bits):
a 00000101 5
| b 00001000 8
------------
00001101 13
Then the bitwise NOT:
~ 00001101 13
----------
11110010 -14
Performing a bitwise NOT on a positive value does not give you its negative value, it gives you one less.
Upvotes: 0
Reputation: 213276
Because you have a 2's complement computer.
0101 | 1000 = 1101
= 13 dec. ~
and you get 1111....0010
. For the same reason as ~0
gives 2's complement -1
and not -0
.
Upvotes: 2
Reputation: 32586
you confuse the complement to one (~) and the complement to two / unary operator -
~(5|8)
is -(5|8) - 1
so -13 - 1
so -14
Upvotes: 0