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

和 XOR 不 或 左/右转


当前回答

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

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

其他回答

数据库世界中的另一个真实应用程序是MySQL,它的数据类型是SET。

位操作符由DBMS存储SET数据类型。设置可以节省空间。

Element    SET Value    Decimal Value
Travel      00000001    1
Sports      00000010    2
Dancing    00000100    4
Fine Dining   00001000  8

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

我们使用位标记,使会话较小的登录权限在我们的内部网站。

加密都是按位操作。

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