[英]C# hexadecimal & comparison
I ran into a bit of code similar to the code below and was just curious if someone could help me understand what it's doing?: 我遇到了一些类似于以下代码的代码,只是好奇是否有人可以帮助我了解它的作用?:
int flag = 5;
Console.WriteLine(0x0E & flag);
// 5 returns 4, 6 returns 4, 7 returns 6, 8 returns 8
Sandbox: https://dotnetfiddle.net/NnLyvJ 沙箱: https : //dotnetfiddle.net/NnLyvJ
This is the bitwise AND operator. 这是按位与运算符。 It performs an AND operation on the bits of a number. 它对数字的位执行“与”运算。
A logical AND operation on two [boolean] values returns True if the two values are True; 如果两个[布尔]值的逻辑与运算为两个,则返回True。 False otherwise. 否则为假。
A bitwise AND operation on two numbers returns a number from all the bits of the two numbers that are 1 (True) in both numbers. 对两个数字进行按位与运算会从两个数字的所有位中返回一个数字,这两个数字中的所有数字均为1(真)。
Example: 例:
5 = 101
4 = 100
AND = 100 = 4
Therefore, 5 & 4
= 4. 因此, 5 & 4
= 4。
This logic is heavily used for storing flags, you just need to assign each flag a power of 2 (1, 2, 4, 8, etc) so that each flag is stored in a different bit of the flags number, and then you just need to do flags & FLAG_VALUE
and if the flag is set, it'll return FLAG_VALUE
, otherwise 0
. 此逻辑大量用于存储标志,您只需要为每个标志分配2的幂(1、2、4、8等),以便将每个标志存储在标志编号的不同位,然后您只需需要做flags & FLAG_VALUE
,如果设置了标志,它将返回FLAG_VALUE
,否则返回0
。
C# provides a "cleaner" way to do this using enum
s and the Flags
attribute. C#使用enum
和Flags
属性提供了一种“更清洁”的方法。
[Flags]
public enum MyFlags
{
Flag0 = 1 << 0, // using the bitwise shift operator to make it more readable
Flag1 = 1 << 1,
Flag2 = 1 << 2,
Flag3 = 1 << 3,
}
void a()
{
var flags = MyFlags.Flag0 | MyFlags.Flag1 | MyFlags.Flag3;
Console.WriteLine(Convert.ToString((int) flags, 2)); // prints the binary representation of flags, that is "1011" (in base 10 it's 11)
Console.WriteLine(flags); // as the enum has the Flags attribute, it prints "Flag0, Flag1, Flag3" instead of treating it as an invalid value and printing "11"
Console.WriteLine(flags.HasFlag(MyFlags.Flag1)); // the Flags attribute also provides the HasFlag function, which is syntactic sugar for doing "(flags & MyFlags.Flag1) != 0"
}
Excuse my bad english. 对不起,我的英语不好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.