166

我想转换longint.

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

什么是最好的方法?

4

8 回答 8

239

做吧(int)myLongValueunchecked它会在上下文(这是编译器的默认值)中完全按照您的意愿(丢弃 MSB 并采用 LSB )。如果值不适合,它将OverflowException在上下文中抛出:checkedint

int myIntValue = unchecked((int)myLongValue);
于 2009-05-13T16:17:05.323 回答
43
Convert.ToInt32(myValue);

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

于 2009-05-13T16:17:52.327 回答
17

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

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
于 2012-11-19T11:18:23.140 回答
12

最安全、最快的方法是在施法前使用位掩码...

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

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

于 2014-08-21T05:35:46.563 回答
9

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

var intValue= (int)(longValue % Int32.MaxValue);
于 2020-05-12T20:53:05.910 回答
3

它可以通过

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.

这里有一个更长的解释。

于 2019-09-16T09:17:50.860 回答
3

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

myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)
于 2019-09-19T12:28:45.833 回答
1

不会

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

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

于 2019-03-02T10:48:11.177 回答