下面的位运算符在现实世界中有哪些用例?

和 XOR 不 或 左/右转


当前回答

您可以使用它们作为一种快速而不常用的散列数据的方法。

int a = 1230123;
int b = 1234555;
int c = 5865683;
int hash = a ^ b ^ c;

其他回答

一个数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

河内塔线性解采用位运算来解决问题。

public static void linear(char start, char temp, char end, int discs)
{
    int from,to;
    for (int i = 1; i < (1 << discs); i++) {
        from = (i & i-1) % 3;
        to = ((i | i-1) + 1) % 3;
        System.out.println(from+" => "+to);
    }
}

这个解决方案的解释可以在这里找到

我将它们用于多选择选项,这样我只存储一个值,而不是10个或更多

当你只想改变微控制器输出的一些位,但要写入的寄存器是一个字节时,你可以这样做(伪代码):

char newOut = OutRegister & 0b00011111 //clear 3 msb's
newOut = newOut | 0b10100000 //write '101' to the 3 msb's
OutRegister = newOut //Update Outputs

当然,许多微控制器允许你单独改变每一位。

Bit fields (flags) They're the most efficient way of representing something whose state is defined by several "yes or no" properties. ACLs are a good example; if you have let's say 4 discrete permissions (read, write, execute, change policy), it's better to store this in 1 byte rather than waste 4. These can be mapped to enumeration types in many languages for added convenience. Communication over ports/sockets Always involves checksums, parity, stop bits, flow control algorithms, and so on, which usually depend on the logic values of individual bytes as opposed to numeric values, since the medium may only be capable of transmitting one bit at a time. Compression, Encryption Both of these are heavily dependent on bitwise algorithms. Look at the deflate algorithm for an example - everything is in bits, not bytes. Finite State Machines I'm speaking primarily of the kind embedded in some piece of hardware, although they can be found in software too. These are combinatorial in nature - they might literally be getting "compiled" down to a bunch of logic gates, so they have to be expressed as AND, OR, NOT, etc. Graphics There's hardly enough space here to get into every area where these operators are used in graphics programming. XOR (or ^) is particularly interesting here because applying the same input a second time will undo the first. Older GUIs used to rely on this for selection highlighting and other overlays, in order to eliminate the need for costly redraws. They're still useful in slow graphics protocols (i.e. remote desktop).

这些只是我最先想到的几个例子——这不是一个详尽的清单。