繁体   English   中英

C#十六进制和比较

[英]C# hexadecimal & comparison

我遇到了一些类似于以下代码的代码,只是好奇是否有人可以帮助我了解它的作用?:

int flag = 5;
Console.WriteLine(0x0E & flag);
// 5 returns 4, 6 returns 4, 7 returns 6, 8 returns 8

沙箱: https//dotnetfiddle.net/NnLyvJ

这是按位与运算符。 它对数字的位执行“与”运算。

如果两个[布尔]值的逻辑与运算为两个,则返回True。 否则为假。

对两个数字进行按位与运算会从两个数字的所有位中返回一个数字,这两个数字中的所有数字均为1(真)。

例:

5   = 101
4   = 100
AND = 100 = 4

因此, 5 & 4 = 4。

此逻辑大量用于存储标志,您只需要为每个标志分配2的幂(1、2、4、8等),以便将每个标志存储在标志编号的不同位,然后您只需需要做flags & FLAG_VALUE ,如果设置了标志,它将返回FLAG_VALUE ,否则返回0

C#使用enumFlags属性提供了一种“更清洁”的方法。

[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"
}

对不起,我的英语不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM