这是将 long 转换为 int 的一种相当轻松的方法,只需提取低 32 位而不抛出异常。没有 64 位除法,没有 try/catch 块,只是位旋转和单个比较。
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
编辑注意:
另一种选择是使用可为空的整数 ( 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 位整数的域之外,则返回值将是一个整数值。