简体   繁体   English

从字节中提取位的效率

[英]Efficiency of extracting a bit from byte

I'm extracting the 8th bit from a byte in C. Here is my example. 我正在从C中的一个字节中提取第8位。这是我的示例。

register unsigned char byte;

int pos = 7;

int x =(byte >> pos) & 1;   //Method I

int y =(byte & 0x80) >> pos;    //Method II

Both techniques will result in the same output, but is one of the methods more efficient than the other? 两种技术都将产生相同的输出,但是其中一种方法是否比另一种方法更有效?

Both will be the same. 两者将是相同的。 Both AND and SHR instructions are 1-clock instructions on intel CPUs. 在Intel CPU上,AND和SHR指令均为1时钟指令。

Bitwise operations a basically one of the fastest things you'll find on a computer. 按位运算基本上是您在计算机上找到的最快的东西之一。 I'd imagine that any difference would be incredibly minor, such that it doesn't really matter. 我以为任何差异都将是非常微小的,因此这并不重要。

If you know the bit you are extracting at compile-time, then either method should have approximately the same speed: 如果您知道在编译时要提取的位,则两种方法的速度应大致相同:

unsigned char val;
const int pos = 4;
...
int x = (val >> pos) & 1;
int y = (val & 0x10) >> pos;

However if you are calculating the position at runtime and not as a constant, doing the AND last should be faster: 但是,如果要在运行时而不是作为常数来计算位置,则执行AND运算应该更快:

unsigned char val;
int pos;
...
/* requires only a shift and AND */
int x = (val >> pos) & 1;
/* requires two shifts and AND */
int y = (val & (1 << pos)) >> pos;

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

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