Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: assign 0xFFFFFFFF to int

Tags:

c#

I want to use HEX number to assign a value to an int:

int i = 0xFFFFFFFF; // effectively, set i to -1

Understandably, compiler complains. Question, how do I make above work?

Here is why I need this. WritableBitmap class exposes pixels array as int[]. So if I want to set pixel to Blue, I would say: 0xFF0000FF (ARGB) (-16776961)

Plus I am curious if there is an elegant, compile time solution.

I know there is a:

int i = BitConverter.ToInt32(new byte[] { 0xFF, 0x00, 0x00, 0xFF }, 0);

but it is neither elegant, nor compile time.

like image 447
THX-1138 Avatar asked Jul 23 '11 00:07

THX-1138


2 Answers

Give someone a fish and you feed them for a day. Teach them to pay attention to compiler error messages and they don't have to ask questions on the internet that are answered by the error message.

int i = 0xFFFFFFFF; 

produces:

Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists 
(are you missing a cast?)

Pay attention to the error message and try adding a cast:

int i = (int)0xFFFFFFFF; 

Now the error is:

Constant value '4294967295' cannot be converted to a 'int' 
(use 'unchecked' syntax to override)

Again, pay attention to the error message. Use the unchecked syntax.

int i = unchecked((int)0xFFFFFFFF); 

Or

unchecked
{
    int i = (int)0xFFFFFFFF; 
}

And now, no error.

As an alternative to using the unchecked syntax, you could specify /checked- on the compiler switches, if you like to live dangerously.

Bonus question:

What makes the literal a uint in the first place?

The type of an integer literal does not depend on whether it is hex or decimal. Rather:

  • If a decimal literal has the U or L suffixes then it is uint, long or ulong, depending on what combination of suffixes you choose.
  • If it does not have a suffix then we take the value of the literal and see if it fits into the range of an int, uint, long or ulong. Whichever one matches first on that list is the type of the expression.

In this case the hex literal has a value that is outside the range of int but inside the range of uint, so it is treated as a uint.

like image 65
Eric Lippert Avatar answered Nov 20 '22 18:11

Eric Lippert


You just need an unchecked cast:

unchecked
{
    int i =  (int)0xFFFFFFFF;

    Console.WriteLine("here it is: {0}", i);
}
like image 15
Paul Keister Avatar answered Nov 20 '22 18:11

Paul Keister