简体   繁体   中英

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)? When I loop only i<31 it is giving 2147483647. Why is it so?

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 .

You may want to check out Two's Complement .

In your printf statement you are using %d , which prints a signed 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. No more sign bit and the value you are looking for.

You should be using an unsigned int anyway for samp .

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

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