Search code examples
c#bitmask

What is the most convenient way to setup a bitmask to use against an int equal to 0xFFFF0000


For some reason C# does not want to implicitely use 0xFFFF0000 as a value as it is above int.MaxValue. What I would expect is that it could be casted somehow to be the corresponding negative value.

I have to do some bitwise operations and I would like to set an int as 0xFFFF0000 just for this purpose independently of the sign.

However this will not compile:

int leftmask = 0xFFFF0000;

The error is:

Error   1   Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists (are you missing a cast?) c:\....\Program.cs  127 28  

Solution

  • Well, as you said, that value won't "fit" to integer by default,

    if you don't care about the semantics, you can just force it:

    int leftmask = unchecked((int)0xFFFF0000);