扩展阅读:
- 一位园友的总结: https://www.cnblogs.com/xiaohutu/p/10951911.html
- 斯坦福的位运算技巧大全:http://graphics.stanford.edu/~seander/bithacks.html
1.判断符号是否相同(Math.Sign)
a^b >= 0
2.求两个整数的平均值
(x + y) >> 1;
3.判断基偶(比%2要快)
a & 1
结果0为偶数,为1是基数
4.判断一个数是不是2的幂
((x&(x-1))==0)&&(x!=0)
5.对一个32位数快速sign,正数为1负数为-1
x>>31 | 1
6.借助德布莱英序列(DeBruijn),从右取当前Mask第一个1的位数(注意传入值必须是uint,否则出错):
int[] multiplyDeBruijnBitPosition = new int[32]
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
uint x = 1 << 7;
uint magicNumber = 0x077CB531;
int bitPosition = multiplyDeBruijnBitPosition[((x & (uint) -x) * magicNumber) >> 27];
Debug.Log("bitPosition: " + bitPosition);//7