简体   繁体   English

C 中按位运算符的性能

[英]Performance of bitwise operators in C

What is the fastest way to make the last 2 bits of a byte zero?使字节的最后 2 位为零的最快方法是什么?

x = x >> 2 << 2;

OR或者

x &= 252;

Is there a better way?有没有更好的办法?

Depends on many factors, including the compiler, the machine architecture (ie processor).取决于很多因素,包括编译器、机器架构(即处理器)。

My experience is that我的经验是

x &= 252; // or...
x &= ~3;  

are more efficient (and faster) than

x = x >> 2 << 2; x = x >> 2 << 2;

If your compiler is smart enough, it might replace如果你的编译器足够聪明,它可能会取代

x = x >> 2 << 2;

by经过

x &= ~3;

The later is faster than the former, because the later is only one machine instruction, while the former is two.后者比前者快,因为后者只有一条机器指令,而前者是两条。 And all bit manipulation instructions can be expected to execute in precisely one cycle.并且所有位操作指令都可以预期在精确的一个周期内执行。


Note:笔记:
The expression ~3 is the correct way to say: A bit mask with all bits set but the last two.表达式~3是正确的说法:一个位掩码,所有位都设置,但最后两个位。 For a one-byte type, this is equivalent to using 252 as you did, but ~3 will work for all types up to int .对于一字节类型,这相当于像您一样使用252 ,但~3将适用于所有类型,直到int If you need to specify such a bitmask for a larger type like a long , add the appropriate suffix to the number, ~3l in the case of a long .如果您需要为更大的类型(如long指定这样的位掩码,请为数字添加适当的后缀,在long的情况下为~3l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM