yasar - 1 year ago 59

C Question

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?

Answer Source

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

Clearly adds `data[c]`

to `sum`

if and only if `data[c]`

is greater or equal than 128. It's easy to show that

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

Is equivalent (when `data`

only holds positive values, which it does):

`data[c] - 128`

is positive if and only if `data[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 `sum`

either `0 & data[c]`

(so zero) in the case that `data[c] < 128`

or `0xFFFFFFFF & data[c]`

(so `data[c]`

) in the case that `data[c] >= 128`

.