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

和 XOR 不 或 左/右转


当前回答

当我第一次开始C编程时,我理解了真值表和所有的东西,但直到我读了这篇文章http://www.gamedev.net/reference/articles/article1563.asp(它给出了真实的例子),我才完全了解如何实际使用它。

其他回答

下面是一些处理将标志存储为单个位的常见习惯用法。

enum CDRIndicators {
  Local = 1 << 0,
  External = 1 << 1,
  CallerIDMissing = 1 << 2,
  Chargeable = 1 << 3
};

unsigned int flags = 0;

设置Chargeable标志:

flags |= Chargeable;

清除CallerIDMissing标记:

flags &= ~CallerIDMissing;

测试CallerIDMissing和Chargeable是否设置:

if((flags & (CallerIDMissing | Chargeable )) == (CallerIDMissing | Chargeable)) {

}

一个非常具体的例子,但我用它们让我的数独求解器运行得更快(我和一个朋友进行了比赛)

每一列、行和3x3都表示为一个无符号整数,当我设置数字时,我会为相关列、行和3x3平方中设置的数字标记适当的位。

这样就很容易看到我可以在给定的正方形中放置什么可能的数字,因为我将右边的列、行和3x3的正方形放在一起,然后不这样做,留下一个表示给定位置可能的合法值的掩码。

希望大家能理解。

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

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

我经常使用位操作将选项的组合存储在一个整数中。

int options = 0;

其中OPTION1可以定义为1,OPTION2定义为2,OPTION3定义为4,OPTION4定义为8,OPTION5定义为16,…

void addOption(int option)将使用|操作符向options中添加一个选项。

boolean hasOption(int option)将使用&操作符来测试选项中的选项。

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

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.

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