Question

I want to convert long to int.

If the value of long > int.MaxValue, I am happy to let it wrap around.

What is the best way?

Was it helpful?

Solution

Just do (int)myLongValue. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked context (which is the compiler default). It'll throw OverflowException in checked context if the value doesn't fit in an int:

int myIntValue = unchecked((int)myLongValue);

OTHER TIPS

Convert.ToInt32(myValue);

Though I don't know what it will do when it's greater than int.MaxValue.

Sometimes you're not actually interested in the actual value, but in its usage as checksum/hashcode. In this case, the built-in method GetHashCode() is a good choice:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

The safe and fastest way is to use Bit Masking before cast...

int MyInt = (int) ( MyLong & 0xFFFFFFFF )

The Bit Mask ( 0xFFFFFFFF ) value will depend on the size of Int because Int size is dependent on machine.

Wouldn't

(int) Math.Min(Int32.MaxValue, longValue)

be the correct way, mathematically speaking?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top