2009-03-04 8 views
1

私はフラグ列挙型とビット演算子について読んで、このコードに出くわした:ビット単位または|オペレータは?

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

私は包括的またはステートメントと&は存在しないことができる方法がある理由についてどこかで読んすることはできませんが、記事を見つける。誰かが私の記憶をリフレッシュして推論を説明できますか?

また、どうすればいいですか?例えば。 dropdown1 =「こんにちは」及び/又はdropdown2 =「こんにちは」....

おかげ

+0

私は、あなたの質問をうまくすることはできませんどのように何かをすることができ、およびまたは?確かに、それはちょうどか? – Mez

+0

@マーティン - 私は彼が口頭の言い回し "および/または" – Dana

答えて

13

最初の質問:

|は、ビット単位で行いますか。第1の値または第2の値に設定されている場合、結果にビットが設定されます。 (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はそうではありません(ビット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番目の質問:

私はあなたが言うときだと思う "および/または" あなたが意味する "1を、他のまたは両方"。これはまさに||(または演算子)の機能です。 「どちらか一方ではなく、両方ではない」と言う場合は、^(排他的または操作者)を使用します。

真理値表(真== 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

上またはビット単位であるか、論理的ではない場合、または。 1 | 2は3に相当する(1 & 2 = 0)。

ビット単位操作の詳細については、http://en.wikipedia.org/wiki/Bitwise_operationを参照してください。

0

ここでは2つの異なる質問がありますが、#2に答えるために、ほとんどのプログラミング言語に見られるような論理ORがあります。

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

排他的論理和しかし手段、「どちらか一方ではなく両方」。

1

Enumeration Types。 Enumeration Types as Bit Flagsセクションを見てください。これは、例としてORとAND NOT bの例を示しています。

関連する問題