これは、long を int にダウン キャストするかなり簡単な方法で、例外をスローせずに下位 32 ビットを抽出するだけです。64 ビットの除算も、try/catch ブロックもありません。ビットをいじるだけで、比較は 1 回だけです。
Private Function CastLongToInt(x As Long) As Integer
Dim value As Integer = CType(x And &H7FFFFFFFL, Integer) ' get the low order 31 bits
' If bit 32 (the sign bit for a 32-bit signed integer is set, we OR it in
If (0 <> (x And &H80000000L)) Then
value = value Or &H80000000I
End If
Return value
End Function
これは、これまで以上に単純な表現です — ちょっといじるだけです。いいえ、比較はまったくありません。2 つの 16 ビット ニブルを取得し、それらを最終的な値に組み立てます。
Private Function CastLongToInt(x As Long) As Integer
Dim hiNibble As Integer = &HFFFFL And (x >> 16)
Dim loNibble As Integer = &HFFFFL And x
Dim value As Integer = (hiNibble << 16) Or loNibble
Return value
End Function
注意するように編集:
もう 1 つのオプションは、null 許容整数 ( System.Nullable<int>
) を使用することです。VB.Net では、次のようになります。
Private Function TryCastLongToInt(x As Long) As Integer?
Dim value As Integer?
Try
value = CType(x, Integer)
Catch
' This exception intentionall swallowed here
End Try
Return value
End Function
または、意図的に例外をキャッチして飲み込むという概念に悩まされている場合:
Private Function TryCastLongToInt(x As Long) As Integer?
If (x < Integer.MinValue) Then Return Nothing
If (x > Integer.MaxValue) Then Return Nothing
Return x
End Function
どちらの方法でも、戻り値は整数値になるかNothing
、64 ビット値が 32 ビット整数のドメイン外にある場合に返されます。