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

和 XOR 不 或 左/右转


当前回答

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

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

}

其他回答

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

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

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

不久前,我在维基上写了一篇小文章,展示了一个二进制的作者/读者。它在位级上工作,并展示了如何使用位操作符来打包数据。这可能是一个“现实世界”的例子,因为它在游戏中也有应用。

如果你想计算你的数字mod(%) 2的某次方,你可以使用yourNumber & 2^N-1,在这种情况下,它与yourNumber % 2^N相同。

number % 16 = number & 15;
number % 128 = number & 127;

这可能只是作为模数运算的一种替代品有用,它的红利很大,是2^N。但即便如此,在我在。net 2.0上的测试中,它相对于模运算的速度提升也可以忽略不计。我怀疑现代编译器已经执行了这样的优化。有人知道更多吗?

它在sql关系模型中也很方便,假设你有以下表:BlogEntry, BlogCategory

传统上,你可以使用BlogEntryCategory表在它们之间创建一个n-n关系 或者当没有那么多的BlogCategory记录时,你可以在BlogEntry中使用一个值来链接到多个BlogCategory记录,就像你会用标记的枚举做的那样, 在大多数RDBMS中,也有一个非常快速的操作符来选择'标记'列…