質問

フラグ列挙型とビット演算子について読んでいて、このコードに出くわしました:

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

包括的またはステートメントがある理由と、&を使用できないが記事を見つけることができない理由についてどこかを読みました。誰かが私の記憶をリフレッシュして理由を説明してもらえますか?

また、どのように言うことができますか?例えば。 dropdown1 =" hello"の場合および/またはdropdown2 =" hello" ....

ありがとう

役に立ちましたか?

解決

最初の質問:

A | はビット単位のORを行います。最初の値または2番目の値に設定されている場合、結果にビットが設定されます。 ( 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 に対応するビットが設定されているかどうかをテストしています。値 Read および ReadWrite は両方ともこのテストに合格します(両方ともビット0が設定されています)。 Write はしません(ビット0が設定されていません)。

// 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

2番目の質問:

「および/または」と言うとき、「一方、他方、または両方」を意味すると思います。これはまさに || (または演算子)が行うことです。 「一方ではなく両方で」と言うには、 ^ (排他的または演算子)を使用します。

真理値表(true == 1、false == 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)

他のヒント

上記のorはビット単位のorであり、論理orではありません。 1 | 2は3と同等です(1& 2 = 0の場合)。

より良い方法については、 http://en.wikipedia.org/wiki/Bitwise_operation をご覧ください。ビット演算の説明。

列挙型。ビットフラグとしての列挙型のセクションをご覧ください。ORの例とAND NOT bの例が示されています。

さて、ここには2つの異なる質問がありますが、#2に答えるには、ほとんどのプログラミング言語で見られる論理ORがあなたの意味するものであり、そして/または、私は思います。

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

Exclusive-ORとは、「両方ではなくどちらか一方」を意味します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top