下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
我经常使用位操作将选项的组合存储在一个整数中。
int options = 0;
其中OPTION1可以定义为1,OPTION2定义为2,OPTION3定义为4,OPTION4定义为8,OPTION5定义为16,…
void addOption(int option)将使用|操作符向options中添加一个选项。
boolean hasOption(int option)将使用&操作符来测试选项中的选项。
其他回答
一个常见的用法是对齐,例如我需要我的数据在4字节或16字节的边界上对齐。这在RISC处理器中非常常见,其中未对齐的加载/存储要么代价高昂(因为它触发了一个异常处理程序,然后需要修复未对齐的加载),要么根本不允许。
对于任何以2为幂的对齐,下一个对齐的pos可以计算如下:
aligned_offset = alignment + ((current_offset - 1) & ~(alignment - 1))
所以在4字节对齐和当前偏移量为9的情况下:
aligned_offset = 4 + ((9-1) & ~(4-1)) = 4 + (8 & 0xFFFFFFFC) = 4+ 8 = 12
所以下一个4字节的对齐偏移量是12
我的问题在现实世界中是有用的 只响应第一个WM_KEYDOWN通知?
当在windows C api中使用WM_KEYDOWN消息时,第30位指定前一个键的状态。如果在发送消息之前键为down,则值为1;如果键为up,则值为0
这是一个从字节格式的位图图像中读取颜色的例子
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.
我希望这个小例子可以帮助....
它在sql关系模型中也很方便,假设你有以下表:BlogEntry, BlogCategory
传统上,你可以使用BlogEntryCategory表在它们之间创建一个n-n关系 或者当没有那么多的BlogCategory记录时,你可以在BlogEntry中使用一个值来链接到多个BlogCategory记录,就像你会用标记的枚举做的那样, 在大多数RDBMS中,也有一个非常快速的操作符来选择'标记'列…
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).
这些只是我最先想到的几个例子——这不是一个详尽的清单。