下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
数据库世界中的另一个真实应用程序是MySQL,它的数据类型是SET。
位操作符由DBMS存储SET数据类型。设置可以节省空间。
Element SET Value Decimal Value
Travel 00000001 1
Sports 00000010 2
Dancing 00000100 4
Fine Dining 00001000 8
其他回答
我使用它们作为选项处理程序,例如在访问控制列表中描述特定的资源。
看看这篇文章http://planetozh.com/blog/2006/05/php-bitwise-operators-example-of-use/
Edit:还有一个链接: http://blog.code-head.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php
Bitwise operators are useful for looping arrays which length is power of 2. As many people mentioned, bitwise operators are extremely useful and are used in Flags, Graphics, Networking, Encryption. Not only that, but they are extremely fast. My personal favorite use is to loop an array without conditionals. Suppose you have a zero-index based array(e.g. first element's index is 0) and you need to loop it indefinitely. By indefinitely I mean going from first element to last and returning to first. One way to implement this is:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
if (i >= arr.length)
i = 0;
}
这是最简单的方法,如果你想避免if语句,你可以像这样使用模方法:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
i = i % arr.length;
}
这两种方法的缺点是,模运算符是昂贵的,因为它在整数除法后寻找余数。第一个方法在每次迭代中运行if语句。然而,如果你的数组长度是2的幂,你可以很容易地生成一个像0 ..长度- 1,使用&(位和)操作符,如I & Length。知道了这些,上面的代码就变成了
int[] arr = new int[8];
int i = 0;
while (true){
print(arr[i]);
i = i + 1;
i = i & (arr.length - 1);
}
下面是它的工作原理。在二进制格式中,所有2的幂减去1的数都只用1表示。例如,二进制的3是11,7是111,15是1111,等等,你懂的。现在,如果你用任意一个数对一个只由1组成的二进制数,会发生什么?假设我们这样做:
num & 7;
如果num小于或等于7,那么结果将是num,因为每个加1的&-ed就是它自己。如果num大于7,在&操作期间,计算机将考虑7的前导零,当然,在&操作后,这些前导零将保持为零,只有后面的部分将保留。比如二进制的9和7
1001 & 0111
结果将是0001,它是十进制的1,并定位数组中的第二个元素。
我使用它们来实现快速BCD计算(会计师和审计员会对fp舍入感到不安)。
一个数x是2的幂吗?(例如,在计数器递增的算法中很有用,并且一个操作只执行对数次)
(x & (x - 1)) == 0
整数x的最高位是哪位?(例如,这可以用来找出比x大的2的最小次幂)
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return x - (x >>> 1); // ">>>" is unsigned right shift
整数x的最小1位是哪一位?(帮助找出能被2整除的次数。)
x & -x
您可以使用它们作为一种快速而不常用的散列数据的方法。
int a = 1230123;
int b = 1234555;
int c = 5865683;
int hash = a ^ b ^ c;