سؤال

اريد التحويل long إلى int.

إذا كانت قيمة long > int.MaxValue, ، يسعدني أن أتركه يلفها.

ما هي أفضل طريقة؟

هل كانت مفيدة؟

المحلول

فقط افعل (int)myLongValue. سيفعل ما تريده بالضبط (تجاهل MSBs وأخذ LSBs) في unchecked السياق (وهو المترجم الافتراضي). سوف يرمي OverflowException في checked السياق إذا كانت القيمة لا تتناسب مع int:

int myIntValue = unchecked((int)myLongValue);

نصائح أخرى

Convert.ToInt32(myValue);

على الرغم من أنني لا أعرف ماذا ستفعل عندما يكون أكبر من 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?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top