I'm repeating what a few have said already, but I hope that this sums it up...
I know that the bitwise AND of 8 and 4 will return 0 or false and the
bitwise AND of 8 and 9 will return 1 or true but I don't know how to write
the synax for it in C#. I have a value that ranges from 0 to 15 and I need
to compare it to 15 in order to find if it contains the values 1, 2, 4, or
8.
In c/c++ true and false can be used as ints, but in c#, true and false are
of type bool, which is not compatible with int. To get a bool from a number,
you must do a omparison with 0.
eg.
if ((0x11 & 0x01) != 0)
{
Console.WriteLine("True");
}
Note that you should almost always use != 0 to test for true, rather than ==
1 (or == 0x10, or whatever).
C# is so strict about this, that it doesn't even permit a cast from int to
bool. (eg. (bool) 5 won't compile). WTG.
To represent it more graphically, the value 1010 when ANDed with 1000 or
0010 will produce either true or a value greater than 0. I believe the
operator I need to use is &. Can anyone tell me how this is done?
The operators you need are & and |, for the bitwise operations, and == and
!= to get the boolean.
You should use an enum to define your bitwise constants.
This program shows how it's down...note particularly the function
"Eligible", which I discuss below...
class BitwiseExample
{
// Declare an enum with fixed bit settings
enum EmploymentBasis
{
None = 0,
FullTime = 1,
PartTime = 2,
Casual = 4,
Temporary = 8,
}
// Use bitwise operations to test set inclusion.
// Return true if the Employment Basis is FullTime
// or ParTime.
static bool Eligible(EmploymentBasis e)
{
return ((e &
(EmploymentBasis.FullTime |
EmploymentBasis.PartTime))
!= 0);
}
public static void Main()
{
// Use our bitwise test for set inclusion.
EmploymentBasis emp1 = EmploymentBasis.FullTime;
EmploymentBasis emp2 = EmploymentBasis.Casual;
Console.WriteLine(
"emp1 eligible for retirement benefits = " + Eligible(emp1));
Console.WriteLine(
"emp2 eligible for retirement benefits = " + Eligible(emp2));
}
}
Output:
emp1 eligible for retirement benefits = True
emp2 eligible for retirement benefits = False
This function shows how to use the &, | and != operators. We use | to build
up a set (FullTime | PartTime), we & to test for inclusion in the set, and we
use != to get a boolean.
static bool Eligible(EmploymentBasis e)
return ((e &
(EmploymentBasis.FullTime |
EmploymentBasis.PartTime))
!= 0);
I've seen in the help files the [Flags] attribute, which is intended for
bitwise enums, and would be used like this
[Flags]
enum EmploymentBasis
{
}
but it is not clear what it does. My example program worked fine without it.
Cheers,
Javaman