我想转换long
为int
.
如果long
>的值int.MaxValue
,我很乐意让它环绕。
什么是最好的方法?
做吧(int)myLongValue
。unchecked
它会在上下文(这是编译器的默认值)中完全按照您的意愿(丢弃 MSB 并采用 LSB )。如果值不适合,它将OverflowException
在上下文中抛出:checked
int
int myIntValue = unchecked((int)myLongValue);
Convert.ToInt32(myValue);
虽然我不知道当它大于 int.MaxValue 时它会做什么。
有时您实际上并不对实际值感兴趣,而是对它作为checksum/hashcode的用法感兴趣。在这种情况下,内置方法GetHashCode()
是一个不错的选择:
int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
最安全、最快的方法是在施法前使用位掩码...
int MyInt = (int) ( MyLong & 0xFFFFFFFF )
位掩码 ( 0xFFFFFFFF
) 值将取决于 Int 的大小,因为 Int 大小取决于机器。
一种可能的方法是使用模运算符仅让值保持在 int32 范围内,然后将其强制转换为 int。
var intValue= (int)(longValue % Int32.MaxValue);
它可以通过
Convert.ToInt32 方法
但是如果它的值超出 Int32 类型的范围,它会抛出一个 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.
这里有一个更长的解释。
如果值超出整数范围,则以下解决方案将截断为 int.MinValue/int.MaxValue。
myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)
不会
(int) Math.Min(Int32.MaxValue, longValue)
从数学上讲,是正确的方法吗?