C#位运算符在char上

Jon*_*ter 1 c# bit-manipulation char

我有一些旧的C代码正在转换为C#.有很多按位运算符,比如这个

const unsigned char N = 0x10;
char C;
.....
if (C & N)
{
   .....
}
Run Code Online (Sandbox Code Playgroud)

在C#中,这相当于什么呢?例如,第一行在C#中无效,因为编译器说没有从int到char的转换.在C#中,unsigned也不是有效的运算符.

xan*_*tos 9

const char N = (char)0x10;
Run Code Online (Sandbox Code Playgroud)

要么

const char N = '\x10';
Run Code Online (Sandbox Code Playgroud)

if ((C & N) != 0) // Be aware the != has precedence on &, so you need ()
{
}
Run Code Online (Sandbox Code Playgroud)

但请注意,char在C中是1个字节,在C#中它是2个字节,所以也许你应该使用byte

const byte N = 0x10;
Run Code Online (Sandbox Code Playgroud)

但也许你想使用标志,所以你可以使用enum:

[Flags]
enum MyEnum : byte
{
    N = 0x10
}

MyEnum C;

if (C.HasFlag(MyEnum.N))
{
}
Run Code Online (Sandbox Code Playgroud)

(注意Enum.HasFlag是在C#4.0中引入的)