public class EnumTest { [Fact] public void EnumOR() { var mix = TestEnum.apple | TestEnum.orange; Assert.True((mix & TestEnum.apple) != 0); Assert.True((3 & 2) != 0); Assert.True((3 & (int)TestEnum.apple) != 0); Assert.True((mix & TestEnum.tomato) == 0); Assert.True((3 & (int)TestEnum.tomato) == 0); Assert.True(mix.HasFlag(TestEnum.orange)); Assert.True(mix.ToString()== "apple, orange"); Assert.True((int)mix == 3); } [Flags] public enum TestEnum { apple=1, orange=2, potato=4, tomato=8 } }
原文:https://stackoverflow.com/questions/3883384/practical-applications-of-bitwise-operations
I use bitwise operators for security in my applications. I'll store the different levels inside of an Enum:
[Flags]
public enum SecurityLevel
{
User = 1, // 0001
SuperUser = 2, // 0010
QuestionAdmin = 4, // 0100
AnswerAdmin = 8 // 1000
}
And then assign a user their levels:
// Set User Permissions to 1010
//
// 0010
// | 1000
// ----
// 1010
User.Permissions = SecurityLevel.SuperUser | SecurityLevel.AnswerAdmin;
And then check the permissions in the action being performed:
// Check if the user has the required permission group
//
// 1010
// & 1000
// ----
// 1000
if( (User.Permissions & SecurityLevel.AnswerAdmin) == SecurityLevel.AnswerAdmin )
{
// Allowed
}
public class EnumTest { [Fact] public void EnumOR() { var mix = TestEnum.apple | TestEnum.orange; Assert.True((mix & TestEnum.apple) != 0); Assert.True((3 & 2) != 0); Assert.True((3 & (int)TestEnum.apple) != 0); Assert.True((mix & TestEnum.tomato) == 0); Assert.True((3 & (int)TestEnum.tomato) == 0); Assert.True(mix.HasFlag(TestEnum.orange));
Assert.True(mix.ToString()== "apple, orange"); Assert.True((int)mix == 3); }
[Flags] public enum TestEnum { apple=1, orange=2, potato=4, tomato=8 } }