什么是按位或| 操作员呢?

我正在阅读有关标志枚举和按位运算符的信息,并且遇到了以下代码:

enum file{ read = 1, write = 2, readandwrite = read | write } 

我在某处读到了为什么有一个包容性或陈述以及如何不能有&,但找不到文章。 有人可以刷新我的记忆并解释推理吗?

另外,我怎么说和/或? 例如。 如果dropdown1 =“你好”和/或dropdown2 =“你好”….

谢谢

第一个问题:

A | 按位或; 如果在第一个值或第二个值中设置了一个位,将在结果中设置一个位。 (您在enums上使用它来创建其他值组合的值)如果您要使用按位,那么它就没有多大意义。

它使用如下:

 [Flags] enum FileAccess{ None = 0, // 00000000 Nothing is set Read = 1, // 00000001 The read bit (bit 0) is set Write = 2, // 00000010 The write bit (bit 1) is set Execute = 4, // 00000100 The exec bit (bit 2) is set // ... ReadWrite = Read | Write // 00000011 Both read and write (bits 0 and 1) are set // badValue = Read & Write // 00000000 Nothing is set, doesn't make sense ReadExecute = Read | Execute // 00000101 Both read and exec (bits 0 and 2) are set } // Note that the non-combined values are powers of two, \ // meaning each sets only a single bit // ... // Test to see if access includes Read privileges: if((access & FileAccess.Read) == FileAccess.Read) 

基本上,您可以测试enum是否设置了某些位; 在这种情况下,我们正在测试是否设置了与Read相对应的位。 值ReadReadWrite都将通过此测试(两者都设置为零); Write不会(它没有设置位零)。

 // if access is FileAccess.Read access & FileAccess.Read == FileAccess.Read // 00000001 & 00000001 => 00000001 // if access is FileAccess.ReadWrite access & FileAccess.Read == FileAccess.Read // 00000011 & 00000001 => 00000001 // uf access is FileAccess.Write access & FileAccess.Read != FileAccess.Read // 00000010 & 00000001 => 00000000 

第二个问题:

我想当你说“和/或”时,你的意思是“一个,另一个或两个”。 这正是|| (或运营商)。 要说“一个或另一个,但不是两个”,你要使用^ (独家或opertor)。

真值表(true == 1,false == 0):

  AB | A || B ------|------- OR 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 1 (result is true if any are true) AB | A ^ B ------|------- XOR 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 0 (if both are true, result is false) 

以上或是按位或不符合逻辑或。 1 | 2相当于3(而1和2 = 0)。

有关按位运算的更好说明,请参见http://en.wikipedia.org/wiki/Bitwise_operation 。

枚举类型 。 将枚举类型视为位标志部分,它给出了OR的示例以及AND NOT b的示例。

好吧,这里有两个不同的问题,但回答#2,大多数编程语言中的逻辑OR就是你的意思和/或我想的。

 if (dropdown == "1" || dropdown == "2") // Works if either condition is true. 

但是,“异或”表示“一个或另一个但不是两个”。