Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

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) cast around it like so, 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, hence has a range of -2,147,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!

swine

like image 763
swinefeaster Avatar asked May 17 '11 07:05

swinefeaster


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

As you note, the range of Int32 is -2,147,483,648 to 2,147,483,647, so any number within that range can be held, but ONLY numbers within that range can be held. 4,294,901,760 is greater than 2,147,483,647, so doesn't fit in an Int32.

What to do about this depends on what you want to achieve. If you just want an Int32 with the bit pattern ffff0000, then as suggested use unchecked :

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

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

However! If you actually want the value 4,294,901,760 you should use a datatype appropriate to it - so UInt32.

like image 158
AakashM Avatar answered Oct 25 '22 20:10

AakashM