Home > Tech.Notes > 对位运算

对位运算

近来在做驱动方面的开发, 结果发现对位操作反应比较迟钝, 就从网上搜了些有关位操作的说明复习一下.
[sourcecode language='c']
if (set) {
/* shift 位设置为1 */
val |= (1 << shift);
}
else{
/* shift 位清零 */
val &= ~(1 << shift);
}

[/sourcecode]
Set a bit (where n is the bit number, and 0 is the least significant bit):
[sourcecode language='c']
unsigned char a |= (1 << n);
[/sourcecode]
Clear a bit:
[sourcecode language='c']
unsigned char b &= ~(1 << n);
[/sourcecode]
Toggle a bit: n位的值取反
[sourcecode language='c']
unsigned char c ^= (1 << n);
[/sourcecode]
Test a bit:
[sourcecode language='c']
unsigned char e = d & (1 << n); //d has the byte value.
[/sourcecode]
还有一个对奇偶性进行判断
[sourcecode language='c']
a&1 = 0 // 偶数
a&1 = 1 // 奇数
[/sourcecode]
参考:
1.  http://en.wikipedia.org/wiki/Bit_manipulation

2. 这里面将的比较全也比较详细, 有兴趣的可以看看 http://graphics.stanford.edu/~seander/bithacks.html


Bian Jiang
Blog:  http://www.wifihack.net/

Categories: Tech.Notes Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Additional comments powered by BackType