开发者

Bitwise complement operator

Can you guys please explain the below program

int main() 
{   
 int max = ~0; 
 printf("%d\n",max);    
 return 0; 
}

AFAIK ~ will flip the bits. In this case i.e ~0 will set all the bits into 1. So ma开发者_C百科x variable should contain MAX value but I am getting o/p as -1. So can anyone here please tell me why I am getting o/p as -1.


Why did you expect to obtain the "max value"? In 2's-complement signed representation all-1 bit pattern stands for -1. It is just the way it is.

Maximum value in 2's-complement signed representation is represented by 01111...1 bit pattern (i.e the first bit is 0). What you got is 1111...1, which is obviously negative since the very first bit - sign bit - is 1.

If you want an example where complemented zero produces a "max value", use unsigned representation

int main() {   
  unsigned max = ~0u; 
  printf("%u\n", max);    
}


That is the correct output since you are using the int data type which is signed. You need to read about two's complement negative representation. All one bits is not the maximum negative value, it is -1 as your program outputs. Maximum negative signed value is most significant bit set and all the remaining bits zero, 0x80000000 in the 32-bit case. Maximum positive signed value is 0x7fffffff in the 32-bit case.


The above answers have already covered the reason behind ~0 having value -1.

If you are looking for max integer value, then you can include the limits.h library and use the constants declared in that library

INT_MAX gives you the maximum signed integer value. UINT_MAX gives you the maximum unsigned integer value.

#include <stdio.h>
#include <limits.h>

int main()
{
printf( "Max signed int value: %d \n", INT_MAX);
printf("Max unsigned int value: %u \n", UINT_MAX );
return 0;
}


This question was a long time ago, but for posterity's sake:
It might help you to see it better if you print ~0 as both int and hex as follows:

printf("compliment of zero %d\n", (~0));
printf("compliment of zero 0x%x\n", (~0));

Output:
Compliment of zero -1
Compliment of zero 0xffffffff

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜