简体   繁体   English

C中的位操作

[英]Bit manipulation in c

int samp=0;

for(i=0;i<=31;i++)
{
  samp=samp|1<<i;
}
printf("\ %d\n",samp);

output: 输出:

-1

Why is it giving -1 if I loop till i<=31 (setting all 32 bits to 1)? 如果我循环到i<=31 (将所有32位设置为1),为什么给出-1? When I loop only i<31 it is giving 2147483647. Why is it so? 当我仅循环i<31它会给出2147483647。为什么会这样?

This is happening because the first bit is the sign bit. 发生这种情况是因为第一位是符号位。

When the sign bit is 1 , the number is negative, and 11111111 11111111 11111111 11111111 happens to be the 32-bit representation of the number -1 . 当符号位为1 ,数字为负,并且11111111 11111111 11111111 11111111恰好是数字-1的32位表示形式。

You may want to check out Two's Complement . 您可能要检查出Two's Complement

In your printf statement you are using %d , which prints a signed integer . 在您的printf语句中,您正在使用%d ,它输出一个带符号的integer The output is correct due to the sign bit being set. 由于设置了符号位,因此输出正确。

Change the format string to %u and it will display the unsigned integer value. 将格式字符串更改为%u ,它将显示无符号整数值。 No more sign bit and the value you are looking for. 没有更多的符号位和您想要的值。

You should be using an unsigned int anyway for samp . 无论如何,您都应该将unsigned int用于samp

由于现代计算机中的带符号整数表示为两个补码: http : //en.wikipedia.org/wiki/Two%27s_complement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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