C#位运算符在char上

时间:2011-10-27 09:52:57

标签: c# char bit-manipulation

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

const unsigned char N = 0x10;
char C;
.....
if (C & N)
{
   .....
}

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

1 个答案:

答案 0 :(得分:9)

const char N = (char)0x10;

const char N = '\x10';

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

但要注意C中的char是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中引入的)