我可以将long转换为int吗?

时间:2009-05-13 16:15:22

标签: c# types int type-conversion long-integer

我想将long转换为int

如果long>的值int.MaxValue,我很高兴让它环绕。

最好的方法是什么?

8 个答案:

答案 0 :(得分:200)

(int)myLongValue。它会在unchecked上下文(这是编译器默认值)中完全按照您的要求(丢弃MSB和获取LSB)执行操作。如果该值不适合OverflowException,它会在checked上下文中抛出int

int myIntValue = unchecked((int)myLongValue);

答案 1 :(得分:30)

Convert.ToInt32(myValue);

虽然当它大于int.MaxValue时我不知道它会做什么。

答案 2 :(得分:15)

有时您实际上并不对实际值感兴趣,而是将其用作 checksum / hashcode 。在这种情况下,内置方法GetHashCode()是一个不错的选择:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

答案 3 :(得分:7)

安全且最快捷的方法是在演员之前使用比特掩码......

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

位掩码(0xFFFFFFFF)值将取决于Int的大小,因为Int大小取决于计算机。

答案 4 :(得分:3)

一种可能的方法是使用取模运算符仅让值保持在int32范围内,然后将其强制转换为int。

var intValue= (int)(longValue % Int32.MaxValue);

答案 5 :(得分:0)

不会

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

从数学上来说是正确的方法吗?

答案 6 :(得分:0)

它可以通过

进行转换
  

Convert.ToInt32方法

但是,如果该值超出Int32 Type的范围,它将抛出OverflowException。 基本测试将向我们展示其工作方式:

long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
{
   try {
         result = Convert.ToInt32(number);
        Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                    number.GetType().Name, number,
                    result.GetType().Name, result);
     }
     catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
                    number.GetType().Name, number);
     }
}
// The example displays the following output:
//    The Int64 value -9223372036854775808 is outside the range of the Int32 type.
//    Converted the Int64 value -1 to the Int32 value -1.
//    Converted the Int64 value 0 to the Int32 value 0.
//    Converted the Int64 value 121 to the Int32 value 121.
//    Converted the Int64 value 340 to the Int32 value 340.
//    The Int64 value 9223372036854775807 is outside the range of the Int32 type.

Here有更长的解释。

答案 7 :(得分:0)

如果值超出整数范围,以下解决方案将截断为int.MinValue / int.MaxValue。

myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)