2

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 
6
  • Have you tried uint leftmask = 0xFFFF0000; Commented Sep 14, 2014 at 18:00
  • Yes but some reason it did not like operations with signed int afterwards which is also a bit weird. Commented Sep 14, 2014 at 18:01
  • Instruct the enum to use uint as its base storage type. I forget the exact syntax. Commented Sep 14, 2014 at 18:02
  • Yes unfortunately, this was for an interview on Codibility, and they give me signed ints. I had to submit anyway, no worries I did a << 16 but did not have time to test so I submitted another solution. Commented Sep 14, 2014 at 18:05
  • Out of curiosity, what was the question ? Commented Sep 14, 2014 at 18:27

2 Answers 2

3

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); 
Sign up to request clarification or add additional context in comments.

Comments

3

This will do the trick:

int leftmask = ~0xFFFF; 

1 Comment

I voted up for your solution but accepted Erti-Chris solution as it seems slightly clearer for me, but yours is good also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.