简体   繁体   中英

Code explanation

I don't know if this is the correct SE site for posting, but i'll try either way, from this answer .It is suggested that this

if (data[c] >= 128)
     sum += data[c];

can turn into this:

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

Can someone explain to me how this would work?

The idea behind what is happening is this. Assume data[c] > 128. If that is true, doing data[c] - 128 results in a positive number (ie. the sign bit is 0). Shifting that right 31 times results in a number that is all 0s in binary. So t=00000000000000000000000000000000.

Now, when we do ~t it becomes all 1s and &-ing that with data[c] just gives us data[c] again. Now we add that to the sum and that works just like before.

But what if data[c] < 128? Well that means that data[c] - 128 is negative, giving a 1 as a sign bit. Which means that t=11111111111111111111111111111111. Thus ~t is all 0s. &-ing all 0s with data[c] just gives all 0s again (ie. 0 in decimal). Adding 0 to the sum doesn't change it so all is well.

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