【问题标题】:What does the bitwise or | operator do?什么是按位或 |运营商呢?
【发布时间】:2009-03-04 19:29:33
【问题描述】:

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

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

我在某处读到了为什么有一个包含或语句以及为什么不能有 &,但找不到该文章。有人可以刷新我的记忆并解释原因吗?

另外,我该怎么说和/或?例如。如果 dropdown1="hello" 和/或 dropdown2="hello"....

谢谢

【问题讨论】:

  • 我无法解决您的问题,怎么可能是 and 和 or ?那肯定只是一个或吗?
  • @Martin -- 我以为他指的是口语短语“和/或”

标签: c# .net enums bit-manipulation


【解决方案1】:

第一个问题:

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

它的用法如下:

[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

第二个问题:

我认为当您说“和/或”时,您的意思是“一个、另一个或两者”。这正是||(或运算符)所做的。要说“一个或另一个,但不是两者”,您可以使用 ^(独占或运算符)。

真值表(真==1,假==0):

     A   B | A || B 
     ------|-------
OR   0   0 |    0
     0   1 |    1 
     1   0 |    1
     1   1 |    1 (result is true if any are true)

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

【讨论】:

    【解决方案2】:

    上面的 or 是按位或,而不是逻辑或。 1 | 2 等价于 3(而 1 & 2 = 0)。

    请参阅http://en.wikipedia.org/wiki/Bitwise_operation 以获得有关按位运算的更好解释。

    【讨论】:

      【解决方案3】:

      Enumeration Types。查看 Enumeration Types as Bit Flags 部分,它给出了 OR 的示例以及 AND NOT b 的示例。

      【讨论】:

        【解决方案4】:

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

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

        然而,异或的意思是“一个或另一个,但不是两者兼而有之”。

        【讨论】:

          猜你喜欢
          • 2010-10-24
          • 1970-01-01
          • 1970-01-01
          • 2023-03-04
          • 2017-07-14
          • 2016-04-01
          • 2010-09-07
          • 2015-08-20
          • 2011-11-19
          相关资源
          最近更新 更多