下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
我曾在一些游戏开发书籍中看到它是一种更有效的乘除方法。
2 << 3 == 2 * 8
32 >> 4 == 32 / 16
其他回答
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)将使用&操作符来测试选项中的选项。
按位&用于屏蔽/提取字节的某一部分。
1字节变量
01110010
&00001111 Bitmask of 0x0F to find out the lower nibble
--------
00000010
特别是移位运算符(<< >>)经常用于计算。
Base64编码就是一个例子。Base64编码用于将二进制数据表示为通过电子邮件系统(和其他目的)发送的可打印字符。Base64编码将一系列8位字节转换为6位字符查找索引。位操作,移位,'ing, 'ing, not'ing对于实现Base64编码和解码所需的位操作非常有用。
当然,这只是无数例子中的一个。
通常位运算比乘除运算快。所以如果你需要用一个变量x乘以9,你会用x<<3 + x这将比x*9快几个周期。如果此代码位于ISR中,则可以节省响应时间。
类似地,如果您想使用数组作为循环队列,那么使用逐位操作来处理环绕检查会更快(也更优雅)。(你的数组大小应该是2的幂)。例如:,你可以使用tail = ((tail & MASK) +1)而不是tail = ((tail +1) < size) ?尾+1:0,如果你想插入/删除。
另外,如果您想要一个错误标志将多个错误代码保存在一起,则每个位可以保存一个单独的值。您可以与它与每个单独的错误代码作为检查。这用于Unix错误代码。
此外,n位位图可以是一个非常酷而紧凑的数据结构。如果要分配一个大小为n的资源池,我们可以使用n位表示当前状态。