问题描述
我在读以及它被提及,这code;
如果(数据[C]> = 128)
总和+ =数据[C];
可以用这个来代替;
INT T =(数据[C] - 128)GT;> 31;
总和+ =〜T&安培;数据[C];
我有很难把握这一点。有人可以解释怎么算按位达到什么样的if语句呢?
如果(数据[C]> = 128)
总和+ =数据[C];
显然增加了数据[C]
到之
当且仅当数据[C ]
比128大于或等于这很容易证明
INT T =(数据[C] - 128)GT;> 31;
总和+ =〜T&安培;数据[C];
时当量(当数据
仅持有正面的价值观,这确实):
数据[C] - 128
为正,当且仅当数据[C]
大于或等于比128.算术右移31,变得要么全1(如果它是小于128)或全零(如果它是大于或等于128)。
第二行则增加了之
或者 0安培;数据[C]
(所以零)的情况下数据[C]< 128
或 0xFFFFFFFF的&安培;数据[C]
(所以数据[C]
)的情况下数据[C]> = 128
。
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?
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
.
这篇关于如何if语句和位操作在这个例子中一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!