2011-10-18 88 views
1

我想一個Double變量轉換成8個字節數組,這就是我跟到目前爲止:雙轉換成8個字節數組

Dim b(0 To 7) As Byte 
Dim i As Integer 

dim d as double 
d = 1   ' for simplicity, I sit the variable "d" to 1 

For i = 0 To 7 
    Call CopyMemory(b(i), ByVal VarPtr(d) + i, 1) 
Next i 

' b => [0, 0, 0, 0, 0, 0, 240, 63] 

我做錯了嗎?

回答

5

不要使用一個循環,使用長度參數:

Option Explicit 

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (_ 
    ByRef Destination As Any, _ 
    ByRef Source As Any, _ 
    ByVal Length As Long) 

Sub DblToByte(ByVal D As Double) 
    Dim Bytes(LenB(D) - 1) As Byte 
    Dim I As Integer 
    Dim S As String 

    CopyMemory Bytes(0), D, LenB(D) 

    For I = 0 To UBound(Bytes) 
     S = S & CStr(Bytes(I)) & " " 
    Next 
    MsgBox S 
End Sub 

Private Sub Form_Load() 
    DblToByte 1 
    Unload Me 
End Sub 
+0

的一個例子,[如何再轉換回(http://stackoverflow.com/q/15782705/588306)。 – Deanna

3

你不顯示你的聲明語句,但是可以爲它的不同用途聲明不同的CopyMemory。嘗試:

Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (_ 
               ByVal pDst As Long, _ 
               ByVal pSrc As Long, _ 
               ByVal ByteLen As Long _ 
               )