C#: assign 0xFFFFFFFF to int

Viewed 16603

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.

3 Answers

The unchecked syntax seems a bit gar'ish (!) when compared to the various single-letter numerical suffixes available.

So I tried for a shellfish:

static public class IntExtMethods
{
    public static int ui(this uint a)
    {
        return unchecked((int)a);
    }
}

Then

int i = 0xFFFFFFFF.ui();

Because the lake has more fish.

Note: it's not a constant expression, so it can't be used to initialize an enum field for instance.

Related