Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c - How is if-statement and bitwise operations same in this example?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...