代码之家  ›  专栏  ›  技术社区  ›  Ian G

我能把long转换成int吗?

  •  127
  • Ian G  · 技术社区  · 16 年前

    long int

    &燃气轮机; int.MaxValue ,我很高兴让它结束。

    最好的方法是什么?

    4 回复  |  直到 10 年前
        1
  •  234
  •   Mehrdad Afshari    16 年前

    照办 (int)myLongValue . 它将完全执行您想要的操作(丢弃MSB并接受LSB) unchecked OverflowException 在里面 checked int :

    int myIntValue = unchecked((int)myLongValue);
    
        2
  •  38
  •   Max Schmeling    16 年前
    Convert.ToInt32(myValue);
    

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

        3
  •  17
  •   Omar    12 年前

    校验和/哈希码 . 在本例中,内置方法 GetHashCode()

    int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
    
        4
  •  12
  •   Yu Hao    10 年前

    安全和最快的方法是在施放前使用位屏蔽。。。

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

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

        5
  •  9
  •   Andre    5 年前

    var intValue= (int)(longValue % Int32.MaxValue);
    
        6
  •  2
  •   Clement    5 年前

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

    myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)
    
        7
  •  1
  •   Zoe - Save the data dump 张群峰    6 年前

    不会

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

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

        8
  •  1
  •   nzrytmn    5 年前

    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.
    

    Here