[英]C# hexadecimal & comparison
我遇到了一些類似於以下代碼的代碼,只是好奇是否有人可以幫助我了解它的作用?:
int flag = 5;
Console.WriteLine(0x0E & flag);
// 5 returns 4, 6 returns 4, 7 returns 6, 8 returns 8
這是按位與運算符。 它對數字的位執行“與”運算。
如果兩個[布爾]值的邏輯與運算為兩個,則返回True。 否則為假。
對兩個數字進行按位與運算會從兩個數字的所有位中返回一個數字,這兩個數字中的所有數字均為1(真)。
例:
5 = 101
4 = 100
AND = 100 = 4
因此, 5 & 4
= 4。
此邏輯大量用於存儲標志,您只需要為每個標志分配2的冪(1、2、4、8等),以便將每個標志存儲在標志編號的不同位,然后您只需需要做flags & FLAG_VALUE
,如果設置了標志,它將返回FLAG_VALUE
,否則返回0
。
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"
}
對不起,我的英語不好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.