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

和 XOR 不 或 左/右转


当前回答

我的问题在现实世界中是有用的 只响应第一个WM_KEYDOWN通知?

当在windows C api中使用WM_KEYDOWN消息时,第30位指定前一个键的状态。如果在发送消息之前键为down,则值为1;如果键为up,则值为0

其他回答

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

当我有一堆布尔标记时,我喜欢将它们全部存储在一个整型中。

我用bitwise-AND取出它们。例如:

int flags;
if (flags & 0x10) {
  // Turn this feature on.
}

if (flags & 0x08) {
  // Turn a second feature on.
}

etc.

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).

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

这是一个从字节格式的位图图像中读取颜色的例子

byte imagePixel = 0xCCDDEE; /* Image in RRGGBB format R=Red, G=Green, B=Blue */

//To only have red
byte redColour = imagePixel & 0xFF0000; /*Bitmasking with AND operator */

//Now, we only want red colour
redColour = (redColour >> 24) & 0xFF;  /* This now returns a red colour between 0x00 and 0xFF.

我希望这个小例子可以帮助....

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

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);
    }
}

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