[C#] long을 int로 변환 할 수 있습니까?

나는 변환 할 longint.

long> 의 값을 int.MaxValue감싼다면 기쁘다.

가장 좋은 방법은 무엇입니까?



답변

그냥하세요 (int)myLongValue. unchecked컨텍스트 (컴파일러 기본값) 에서 원하는 것을 정확하게 수행합니다 (MSB를 삭제하고 LSB를 가져 옵니다). 이 던질거야 OverflowExceptionchecked값이에 맞지 않을 경우 상황 int:

int myIntValue = unchecked((int)myLongValue);


답변

Convert.ToInt32(myValue);

int.MaxValue보다 클 때 어떻게 될지 모르겠습니다.


답변

때로는 실제 값에 관심이 없지만 checksum / hashcode 로 사용하는 데 관심이 있습니다. 이 경우 내장 방법 GetHashCode()이 적합합니다.

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();


답변

안전하고 빠른 방법은 전송하기 전에 비트 마스킹을 사용하는 것입니다.

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

0xFFFFFFFFInt 크기는 컴퓨터에 따라 다르므로 비트 마스크 ( ) 값은 Int 크기에 따라 다릅니다.


답변

그것은에 의해 변환 할 수 있습니다

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) Math.Min(Int32.MaxValue, longValue)

수학적으로 말하면 올바른 방법일까요?


답변

값이 정수 범위를 벗어난 경우 다음 솔루션은 int.MinValue / int.MaxValue로 잘립니다.

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