14,302,209 members
Rate this:
See more:
Hi All,

I am try to decode a bit string (ie: 0000,0000,0000,0000) using a hex value for example
0x0400 = 1024 (dec) I need to pick out bits in the past I have done this via the following
```// bit 0
if ((Hexvalue2 & 0x0001) == 0)
{
//MessageBox.Show("bit 0 set");
}
else
{
//MessageBox.Show("bit 0 not set");
}
```

using the pattern 0001,0002,0004,0008 and then 0010, 0020 and so on, I have done this in Turbo C++ (Borland) and it has worked can this method be applied to C# as I can read one byte correctly and the other I can seem to. If it is a zero a label gets one value and if not a label gets another.

Glenn
(Why, Why, I spent half of last night playing with this!)
Posted
BC @ CV 27-Feb-13 9:36am

Yes. You can use bitwise operators to check for bit flags.

Bit Wise Operators

Bit Flag Enums

Rate this:

## Solution 1

Your expression is not correct, it should be
```if (Hexvalue2 & 0x0001)
{
MessageBox.Show("bit 0 is set");
}```

etc.
glennPattonWork 27-Feb-13 9:46am

Hmmm, If I do the above it will only check for the bit being set I also need to take action on the not set case, also won't that cause problems with trying to convert a ulong to a boolean?
I guess I should said so in the question but Hexvalue2 is a ulong.
Richard MacCutchan 27-Feb-13 10:11am

Well for the other case you can either use the appropriate 'not' operator to reverse the test, or add an `else` clause to your `if` statement. As to whether the value is a short or long, it makes no difference, the compiler will generate the correct code.
Richard MacCutchan 27-Feb-13 10:13am

Supplementary note: I'm not sure where the confusion is coming from here, these operators are exactly the same as used in C, C++ etc.