I need to assign constant value in integer (or other data type).
I got "Cannot convert ..." error with the assignment.
enter image description here
Casting doesn't seem to work with "Overflow ..." error.
enter image description here
What's wrong with this?
-
Hi, there! 0xffffffff is over the limit, use ulong and redefine the import function parameters if this is about PInvoke.Mackintoast– Mackintoast2012年02月18日 17:26:56 +00:00Commented Feb 18, 2012 at 17:26
2 Answers 2
You've defined too many Fs in the constant. Using 0xFFFFFFFF the compiler must choose a a storage location that supports a positive value of 0xFFFFFFFF. The max positive value of an Int32 is instead 0x7FFFFFFF and hence the compiler correctly errors. The only types which can hold 0xFFFFFFFF are uint or one of the 64 bit storages.
To fix this just use Int32.MaxValue
int i32 = Int32.MaxValue;
Comments
The maximum (largest positive) number a 32 bit int can represent is 0x7fffffff. The 7 at the front occurs rather than another f is because int is signed, so the top bit represents the sign (positive or negative) of the number.
In your first example the compiler sees a number that can only be represented by an unsigned int, so it assumes it is a UInt32. This cannot be converted to an int, hence the error.
In your second example you are forcing the conversion with a cast, but the number won't fit into an int, so an overflow (number too big) occurs.
To avoid an overflow, options include:
- Assign a -1
- Assign 0xffffffff in an
unchecked {}block so the raw binary value is written without checking for an overflow. This will read back as -1. - Use a wider type that can represent the larger positive number (uint or long, for example). This won't be considered a -1 though, it'll be a large positive value.
2 Comments
0xFFFFFFFF -1 in two's complement which int supports for sure?unchecked { int i = (int) 0xffffffff; } which would skip the overflow check - of course if you read this value back it will be interpreted as (int) -1.