1

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#.

1 Answer 1

8
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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that. I like the Flag option as it is more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.