The bit-domain mark we commonly use is defined based on a positive number, but it can also be defined based on a negative number, and the work is the same as the positive-number sign-out.
For example, to define an eight-bit domain, two options are provided: the highest bit and the lowest Bit is 1. If byte and sbyte are used as the data types behind enumeration, the enumeration should be declared as follows:
[Flags]
Enum A: byte
{
// The original code of 128 is 10000000
High-level = 128,
Low = 1
}
[Flags]
Enum B: sbyte
{
//-128 completion code: 10000000
High =-128,
Low = 1
}
Next, set all the variables to 1 based on the corresponding type, and then determine whether the highest bit and second bit are enabled.
// Set all flag to 1 (Enabled)
// 255 source code: 1111 1111
VaR Afull = (a) 255;
//-1 complement: 1111 1111
VaR bfull = (B) (-1 );
// Enable only the highest and lowest bits through enumeration
VaR amask = A. High | A. low;
VaR bmask = (B. High | B. Low );
// Determine whether the flag is enabled
Console. writeline (Afull & amask) = amask );
Console. writeline (bfull & bmask) = bmask );
Returns true.
In fact, you can convert them to the same type for the same bit operation, for example, convert them to the byte type:
Static void main (string [] ARGs)
{
// Set all flag to 1 (Enabled)
// 255 source code: 1111 1111
VaR Afull = (a) 255;
//-1 complement: 1111 1111
VaR bfull = (B) (-1 );
Doo (byte) Afull );
Doo (byte) bfull );
}
Static void doo (byte B)
{
// 129 source code: 1000 0001
Byte mask = 129;
Console. writeline (B & Mask) = mask );
}
The above Code also outputs two true values. The reason is that when a negative number is forcibly converted to an unsigned number, the binary data behind it is forcibly inserted into the corresponding variable space, so from the perspective of bit field, there is no change. (For more information about the cross-border check of C # forced conversions, refer to this article: http://www.cnblogs.com/mgen/archive/2012/04/08/2438029.html)
The enum. hasflag method added by. Net 4.0 works like this, except that it uses the unsigned long (ulong), for example:
Therefore, we can also write a simple enumeration bit operation auxiliary type, as shown below:
Static class enumhelper
{
// Determine whether the specified flag is included
Public static bool hasflag (long Val, long flag)
{
Return (Val & flag) = flag;
}
// Set the flag
Public static long setflag (long Val, long flag)
{
Return Val | flag;
}
// Cancel the flag
Public static long unsetflag (long Val, long flag)
{
Return Val &~ Flag;
}
}