&是什么和|运营商吗?它们与&&有何不同?和||?迅速 [英] What do the & and | operators do? How are they different from && and ||? Swift
问题描述
我已经看到许多使用|
或&
的实例,但是我不了解它们的用途.我知道&&
和||
的含义,但是我想知道它们与单个字符对应的区别.同样,如果有人可以向我展示使用|
和&
的示例(请在Swift 2中),那将是很棒的.谢谢
I've seen many instances where |
or &
are used, but I haven't understood what they are used for. I know what &&
and ||
mean, but I would like to know the difference between them and their single character counterparts. Also, it would be great if someone could show me examples of where |
and &
are used (in Swift 2 please). Thank you
推荐答案
请参阅按位操作的维基百科页面和 Swift文档对于按位运算符.
See the Wikipedia page on Bitwise Operation and the Swift documentation for bitwise operators.
这些是按位运算符. &
是按位AND,而|
是按位OR.
These are bitwise operators. &
is bitwise AND and |
is bitwise OR.
请参阅以下示例:
0011 (decimal 3)
AND 0010 (decimal 2)
= 0010 (decimal 2)
0101 (decimal 5)
OR 0011 (decimal 3)
= 0111 (decimal 7)
来源:维基百科
以前在StackOverflow上已经讨论了按位运算符的用法:
The uses of bitwise operators have been discussed before on StackOverflow:
- practical applications of bitwise operations
- Using bitwise operations
使用按位异或(不是您的问题,但仍然是一个很酷的逻辑门)引起了我的注意(@ Vilx- 在这里)(我不知道它是如何工作的,但是答案被接受并投票了34次)
A use of bitwise XOR (not in your question, but a cool logic gate anyway) that caught my eye (by @Vilx- here) (I don't know how it works, but the answer was accepted and up-voted 34 times)
If you want to know how it works, there's a nice simple proof over on XOR swap algorithm - Wikipedia
交换两个没有中间变量的整数变量:
Swapping two integer variables without an intermediary variable:
A = A^B // A is now XOR of A and B
B = A^B // B is now the original A
A = A^B // A is now the original B
如果这些操作无济于事,则我已在本文中链接至两次的Wikipedia页面具有应用程序部分,但它们实际上并不适用于高级语言(除非出于某些原因,您希望优化算术以仅使用按位运算).
If these don't help, the Wikipedia page I already linked to twice in this post has an Applications section, but they don't really apply to higher-level languages (unless for some reason you want to optimize your arithmetic to use only bitwise operations).
这篇关于&是什么和|运营商吗?它们与&&有何不同?和||?迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!