提高读取2的整数补码的性能

时间:2013-12-04 15:34:49

标签: performance optimization vb6

我有一个低效的VB6函数来读取2的补码整数。

Private Function Mantis(ByVal HiByte As Byte, ByVal LoByte As Byte, ByVal Range As Single) As Single

    Dim bSam As Integer
    Dim Bits(15) As Boolean

    bSam = (HiByte And &H7F) * &H100 Or LoByte Or (HiByte \ &H80) * &H8000

    Bits(15) = bSam And 32768

    If Bits(15) Then
        If bSam = -32768 Then
            bSam = 0
        Else
            bSam = bSam * -1
        End If
    End If

    Dim I As Integer

    For I = 0 To 14
        Bits(I) = bSam And (2 ^ I)
    Next

    Dim bOut As Long

    If Bits(2) Then bOut = bOut + 5
    If Bits(3) Then bOut = bOut + 10
    If Bits(4) Then bOut = bOut + 20
    If Bits(5) Then bOut = bOut + 39
    If Bits(6) Then bOut = bOut + 78
    If Bits(7) Then bOut = bOut + 156
    If Bits(8) Then bOut = bOut + 313
    If Bits(9) Then bOut = bOut + 625
    If Bits(10) Then bOut = bOut + 1250
    If Bits(11) Then bOut = bOut + 2500
    If Bits(12) Then bOut = bOut + 5000
    If Bits(13) Then bOut = bOut + 10000
    If Bits(14) Then bOut = bOut + 20000
    If Bits(15) Then bOut = bOut * -1

    Mantis = bOut * Range

End Function

如何才能提升性能?我认为可以用一些memcpy或其他API调用替换它,但我不知道哪一个。因为现在它必须测试每个位。

1 个答案:

答案 0 :(得分:0)

VB6的整数类型是16位有符号的二进制补码,所以我不确定所需的所有比特都是需要的。

如果您的数据以两个字节值的形式到达,为什么不能像这样简单:

Private Type IntAsBytes
    LoByte As Byte
    HiByte As Byte
End Type

Private Type IntAsInt
    Int As Integer
End Type

Private Function Mantis( _
    ByVal HiByte As Byte, _
    ByVal LoByte As Byte, _
    ByVal Range As Single) As Single

    Dim AsBytes As IntAsBytes
    Dim AsInt As IntAsInt

    AsBytes.LoByte = LoByte
    AsBytes.HiByte = HiByte
    LSet AsInt = AsBytes
    Mantis = CSng(AsInt.Int) * Range
End Function