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

和 XOR 不 或 左/右转


当前回答

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

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

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

其他回答

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

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

我在为CMS实现安全模型时使用了按位操作。如果用户属于适当的组,就可以访问它的页面。一个用户可以在多个组中,因此我们需要检查用户组和页面组之间是否有交集。因此,我们为每个组分配了一个唯一的2次方标识符,例如:

Group A = 1 --> 00000001
Group B = 2 --> 00000010
Group C = 3 --> 00000100

我们将这些值一起OR,并将值(作为单个int)存储在页面中。例如,如果一个页面可以被a组和B组访问,我们存储值3(二进制是00000011)作为页面访问控制。同样,我们将or组标识符的值存储给用户,以表示用户所在的组。

因此,要检查给定用户是否可以访问给定页面,只需将这些值与运算在一起,并检查该值是否非零。这是非常快的,因为这个检查是在一条指令中实现的,没有循环,没有数据库往返。

我一直假设按位操作是相当简单的操作,所以当运行时间至关重要时,通过bitset实现的解决方案可以通过恒定的数量提高运行时间,这取决于算法。

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

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

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

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