简体   繁体   中英

bitwise shift with logical OR in C

My original code to take x and turn it into the largest negative int was

*x = 1 <<31 | ~ 1<<31;

which works but when I tried just using

*x = 1 <<31;

It returned the same answer can someone explain why this is so?

If your int is on 32 bits on your architecture, the largest negative int value is obviously 0x80000000.
Let's look at your code and add parenthesis to show the precedence of operators (this is the key here):

*x = 1 <<31 | ~ 1<<31 = (1 << 31) | ((~1) << 31)

The evaluation of the expression ((~1) << 31) gives the result 0x00000000.
So the final result is 1 << 31 = 0x80000000 .

Well if you know two's complement, then you know that for a 32 bit integer, 0x80000000 must be the largest negative value, because if you flip the bits and add one from 0x80000000, you get 0x7fffffff. add one and you get 0x80000000, the largest negative number possible with 32 bits. This has a 1 in the MSB, and there is no way to get larger than this, given that the initial number needs to save a bit for the sign. Your original code just fills the int with 1's and then shifts over 31 resulting in the same final value as *x = 1 <<31;

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