I was reading this answer and it is mentioned that this code;
if (data[c] >= 128)
sum += data[c];
can be replaced with this one;
int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
I am having hard time grasping this. Can someone explain how bitwise operators achieve what if statement does?
Clearly adds
data[c]tosumif and only ifdata[c]is greater or equal than 128. It’s easy to show thatIs equivalent (when
dataonly holds positive values, which it does):data[c] - 128is positive if and only ifdata[c]is greater or equal than 128. Shifted arithmetically right by 31, it becomes either all ones (if it was smaller than 128) or all zeros (if it was greater or equal to 128).The second line then adds to
sumeither0 & data[c](so zero) in the case thatdata[c] < 128or0xFFFFFFFF & data[c](sodata[c]) in the case thatdata[c] >= 128.