使用位操作 [英] Using bitwise operations
问题描述
- 您使用多久位运算黑客做某种
优化?在什么样的情况下是不是真的有用吗?
例如:而不是使用,如果:
Example: instead of using if:
if (data[c] >= 128) //in a loop
sum += data[c];
你写的:
int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
当然,假设它确实为这一具体情况相同的预期效果。结果
Of course assuming it does the same intended result for this specific situation.
- 是否值得呢?我觉得它不可读。你是否经常遇到
这个?结果
请注意:我看到这个code在这里选择的答案:<一href=\"http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array\">Why正在处理一个有序数组比排序的数组更快?
Note: I saw this code here in the chosen answers :Why is processing a sorted array faster than an unsorted array?
推荐答案
按位操作是非常有用,所以教授。克努特写了一本书ABOT他们: http://www.amazon.com/The-Computer-Programming-卷分册/ DP / 0321580508
Bitwise operations are so useful that prof. Knuth wrote a book abot them: http://www.amazon.com/The-Computer-Programming-Volume-Fascicle/dp/0321580508
仅举几个简单的。使用时按位老年退休金计划只是一定要提供有关发生了什么事情上有足够的意见。
Just to mention a few simplest ones: int multiplication and division by a power of two (using left and right shift), mod with respect to a power of two, masking and so on. When using bitwise ops just be sure to provide sufficient comments about what's going on.
不过,你的榜样,数据[C]&GT; 128
不适用IMO,只要保持这种方式。
但是,如果你要计算数据[C] 128%
然后数据[C]放大器; 0x7f的
快得多(其中放;再presents按位AND)。
However, your example, data[c]>128
is not applicable IMO, just keep it that way.
But if you want to compute data[c] % 128
then data[c] & 0x7f
is much faster (where & represents bitwise AND).
这篇关于使用位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!