Libathos
Libathos

Reputation: 3362

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?

Upvotes: -1

Views: 61

Answers (1)

Becuzz
Becuzz

Reputation: 6857

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.

Upvotes: 3

Related Questions