Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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
C#
// 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
Comments
BC @ CV 27-Feb-13 9:36am    
Yes. You can use bitwise operators to check for bit flags.

Bit Wise Operators

Bit Flag Enums

1 solution

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

etc.
 
Share this answer
 
Comments
glennPattonWork3 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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900