2012-02-24 48 views

回答

5

若要將short變量的位設置轉換爲int,最快的解決方案是「快速且骯髒」的CopyMemory方法,如here所示。

Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Bytes As Long) 

Public Sub DoubleToIEEE32(ByVal dValue As Double, ByRef nI1 As Integer, ByRef nI2 As Integer) 
    Dim fValue As Single 
    Dim nInt(1) As Integer 

    fValue = CSng(dValue) 
    CopyMemory nInt(0), fValue, Len(fValue) ‘ copy from Single to Int Array 

    ‘ Internally, the Low Word is word 1 and High Word is word 2. 
    ‘ Swap them to make it like the PLC guys do it. 
    nI1 = nInt(1) 
    nI2 = nInt(0) 
End Sub 

對於讀取和寫入整數的單個位,請參閱here。相關的源代碼是這樣的:

' The ClearBit Sub clears the nth bit (Bit%) 
' of an integer (Byte%). 
Sub ClearBit (Byte%, Bit%) 
    ' Create a bitmask with the 2 to the nth power bit set: 
    Mask% = 2^Bit% 
    ' Clear the nth Bit: 
    Byte% = Byte% And Not Mask% 
End Sub 

' The ExamineBit function will return True or False depending on 
' the value of the nth bit (Bit%) of an integer (Byte%). 
Function ExamineBit% (Byte%, Bit%) 
    ' Create a bitmask with the 2 to the nth power bit set: 
    Mask% = 2^Bit% 
    ' Return the truth state of the 2 to the nth power bit: 
    ExamineBit% = ((Byte% And Mask%) > 0) 
End Function 

' The SetBit Sub will set the nth bit (Bit%) of an integer (Byte%). 
Sub SetBit (Byte%, Bit%) 
    ' Create a bitmask with the 2 to the nth power bit set: 
    Mask% = 2^Bit% 
    ' Set the nth Bit: 
    Byte% = Byte% Or Mask% 
End Sub 

' The ToggleBit Sub will change the state of the 
' nth bit (Bit%) of an integer (Byte%). 
Sub ToggleBit (Byte%, Bit%) 
    ' Create a bitmask with the 2 to the nth power bit set: 
    Mask% = 2^Bit% 
    ' Toggle the nth Bit: 
    Byte% = Byte% Xor Mask% 
End Sub 
+0

正是我在尋找的功能。乾杯! – David 2012-02-24 13:59:14

+0

我剛剛注意到你的答案中沒有包含RtlMoveMemory的CopyMemory別名函數。 – David 2012-02-24 20:02:32

+0

@大衛:從我的部分典型的複製和粘貼錯誤...感謝您修復它! – Treb 2012-02-27 08:59:20