int aNumber;
aNumber = aValue / 2;
aNumber = aValue >> 1;
aNumber = aValue * 2;
aNumber = aValue << 1;
aNumber = aValue / 4;
aNumber = aValue >> 2;
aNumber = aValue * 8;
aNumber = aValue << 3;
// etc.
什么是“最佳”运营方式?什么时候使用位移更好?
最佳答案
如果您使用的是正整数,那么在您给出的示例中,这两者在功能上是等价的(除了最后一个,它应该读作 aValue * 8 == aValue << 3
)。这只有在乘以或除以 2 的幂时才会出现这种情况。
位移永远不会比算术慢。根据您的编译器,算术版本可能会被编译为移位版本,在这种情况下它们都同样有效。否则,位移应该比算术快得多。
然而,算术版本通常更具可读性。因此,我几乎在所有情况下都使用算术版本,并且仅在分析显示语句处于瓶颈时才使用位移位:
Programs should be written for people to read, and only incidentally for machines to execute.
关于c++ - 位移位和算术运算有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2987741/