简体   繁体   中英

A clarification in bitwise operators

I have been performing bitwise operation on a variable.

int p=3,q=5;
int a=~p,b=~q; //complement a and b
printf("%d %d\t%d %d",p,a,q,b);

The theoretical output for 'b' is 10 and in case if it's signed, it has to be -2. But the output is -6.

Can someone explain me the working of it?

~ is the bitwise complement operator in c (or python) which essentially calculates -x - 1 .

So a table would look like:

0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6

In two's complement representation, if a number x's most significant bit is 1, then the actual value would be −(~x + 1).

For instance,

0b11110000 = -(~0b1111 + 1) = -(15 + 1) = -16.

This is a natural representation of negative numbers, because

0000001 =  1
0000000 =  0
1111111 = -1  (wrap around)
1111110 = -2
1111101 = -3 etc.

See http://en.wikipedia.org/wiki/Two%27s_complement for detail.

p is 0b11, so a would be (assuming 16-bit int) 0b1111111111111100 = 0xFFFC if unsigned and -3 if signed.

q is 0b101, so b would be (assuming 16-bit int) 0b1111111111111010 = 0xFFFA if unsigned and -6 if signed.

while taking complement of p(ie 5), you are expecting it to be 1010. ie 10. But the the fact is during one's complement operation, all bits are inverted.

Consider this program.

#include <stdio.h>

int main()
{

int p=5,q=3;
int a=~p,b=~q; //complement a and b
printf("%x %x\t%x %x",p,a,q,b);

return 0;
}

prints

5 fffffffa  3 fffffffc

so while printing using %d, sign is considered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM