简体   繁体   中英

C# Bitwise Operators On char

I have some old C code that is being converted to C#. There is a lot of bitwise operators such as this

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

What would be the equivalent of this in C#? For example, the first line is invalid in C# as the compiler says there is no conversion from int to char. Nor is unsigned a valid operator in C#.

const char N = (char)0x10;

or

const char N = '\x10';

and

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

but be aware that char in C is 1 byte, in C# it's 2 bytes, so perhaps you should use byte

const byte N = 0x10;

but perhaps you want to use flags, so you could use enum :

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

MyEnum C;

if (C.HasFlag(MyEnum.N))
{
}

(note that Enum.HasFlag was introduced in C# 4.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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