C#按位运算符在字符上
问题描述:
我有一些旧的C代码正在转换为C#。有很多像这样的按位运算符:C#按位运算符在字符上
const unsigned char N = 0x10;
char C;
.....
if (C & N)
{
.....
}
在C#中相当于什么?例如,第一行在C#中无效,因为编译器说没有从int到char的转换。在C#中也没有签名有效的运算符。
答
const char N = (char)0x10;
或
const char N = '\x10';
和
if ((C & N) != 0) // Be aware the != has precedence on &, so you need()
{
}
但要知道,char
在C为1个字节,在C#这是2个字节,因此,或许你应该使用byte
const byte N = 0x10;
但也许你想使用的标志,因此您可以使用enum
:
[Flags]
enum MyEnum : byte
{
N = 0x10
}
MyEnum C;
if (C.HasFlag(MyEnum.N))
{
}
(注意:Enum.HasFlag年推出的C#4.0)
感谢您的。我喜欢Flag选项,因为它更具可读性。 – Jonnster