C # - Constant value '4294901760' cannot be converted to 'int'

Hi,

I canโ€™t believe that I am asking such a basic question, but it doesnโ€™t make sense, so :).

In C # on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'. // An explicit conversion exists (are you missing a cast?) public const int RED = 0xffff0000; 

If I put an (int) throw around it like this, I get another error:

 // error CS0221: Constant value '4294901760' cannot be converted to a 'int' // (use 'unchecked' syntax to override) public const int RED = (int)0xffff0000; 

But I know that my int is 32-bit, therefore, has a range from -2147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80). aspx

So what gives?

Thanks in advance!

pigs

+7
source share
5 answers

As you noticed, the Int32 range is -2147,483,648 to 2,147,483,647, so any number within this range can be stored, but ONLY digits in this range can be used. 4,294,901,760 is larger than 2,147,483,647, therefore it does not fit into Int32 .

What to do, it depends on what you want to achieve. If you want just Int32 with the ffff0000 , then as suggested using unchecked :

 int y = unchecked((int)0xffff0000); 

y now has a value of -65536, which is a bit pattern interpreted as a signed integer.

But! If you really need a value of UInt32 , you should use a suitable data type - like UInt32 .

+16
source

int is a signed integer ranging from -2147,483,648 to 2,147,483,647.
What you want is an unsigned integer, i.e. uint , like the first error message.

+4
source

Try using unchecked as suggested by the compiler:

 public const int RED = unchecked((int)0xffff0000); 

This defines RED as -65536, which is 0xffff0000, which is interpreted as a signed int.

+2
source
 public const uint RED = 0xffff0000; 
+2
source

This will lead you to an uncontrollable:

 public const int RED = 0xffff << 16; 
+1
source

All Articles