What exactly is calculated in this expression and why?

#define NP_MAXREADY (((unsigned)(~0)<<1)>>1) 

I take this as: fill register size unsigned int with units, then shake the MSB, getting the maximum value for the signed int. Is it correct? Also, the reason why they do it this way is completely evading me, please enlighten.

+4
source share
2 answers

You can rewrite it as

 #define NP_MAXREADY (((~0u)<<1)>>1) 

then you would notice that the internal shift operation is completely useless, since its only effect is to shift bits of the highest order

 #define NP_MAXREADY ((~0u)>>1) 

which, in turn, is nothing more than

 #define NP_MAXREADY (UINT_MAX/2) 

In addition to what is indicated in another answer, it is not INT_MAX , since first of all it is unsigned here, so the type is different. Then the signed view, compared to unsigned can have padding bits, so you can never be sure that the two have the same value.

+7
source

We will need to see the code that uses it, but the "maximum value of the signed integer" will also be my hunch.

As for why they do it this way, probably because they don’t know about INT_MAX

+7
source

Source: https://habr.com/ru/post/1340714/


All Articles