我可以将 long 转换为 int 吗?

我想把 long转换成 int

如果值为 long > int.MaxValue,我很乐意让它包围起来。

最好的办法是什么?

256573 次浏览

只要做 (int)myLongValue。它将在 unchecked上下文(编译器默认设置)中完全按照您的需要进行操作(丢弃 MSB 和使用 LSBs)。如果值不适合 int,它将在 checked上下文中抛出 OverflowException:

int myIntValue = unchecked((int)myLongValue);
Convert.ToInt32(myValue);

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

有时您实际上对实际值并不感兴趣,而是对它作为 校验和/散列码的用法感兴趣。在这种情况下,内置方法 GetHashCode()是一个很好的选择:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

最安全和最快的方法是使用位掩蔽之前铸造..。

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

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

不会的

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

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

它可以通过

Convert.ToInt32方法

但是,如果该值超出 Int32 Type 的范围,它将抛出 Overflow Exception。 一个基本的测试将向我们展示它是如何工作的:

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.

这里有一个更长的解释。

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

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

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

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