This article has been archived. It is offered "as is" and will no longer be updated.
This article demonstrates how to copy the individual bytes of data in amulti-byte data type, such as a long integer or a single-precision floating-point number, into a byte array. It also illustrates how to take an arrayof bytes and turn it into a specific data type that Visual Basic (and VBA)will recognize.
This code shows how to move the separate bytes of a long integer into afour-element byte array and also how to turn the byte array back into along integer. In a Visual Basic project, place the following code in thedeclarations section:
Private Declare Sub CopyMemory Lib "Kernel32" Alias "RtlMoveMemory" ( _ ByRef Destination As Any, _ ByRef Source As Any, _ ByVal numbytes As Long)
A long integer consists of four bytes. These four bytes are recognized byVisual Basic to be one number. Use the following subroutine to move theindividual bytes into a byte array:
Public Sub LongToBytes(ByRef TheArray() As Byte, ByRef TheLong As Long) Call CopyMemory(TheArray(LBound(TheArray)), TheLong, 4) End Sub
The first parameter passed to CopyMemory is the first element of the arrayinto which the bytes will be stored. (NOTE: The entire array is passed tolongToBytes.) The second parameter is the source variable. The thirdparameter is how many bytes will be moved. Because a long integer consistsof four bytes, this parameter has been set to 4.
To go the other way, turning a byte array back into a long integervariable, use the following code:
Public Function BytesToLong(TheArray() As Byte) As Long Dim TempLong As Long Call CopyMemory(TempLong, TheArray(LBound(TheArray)), 4) BytesToLong = TempLong End Function
NOTE: As with any API call, passing improper memory addresses can causedata corruption or could cause your program to terminate abnormally.
For more information on the use of the RtlMoveMemory function in VisualBasic, please see the following article in the Microsoft Knowledge Base:
Microsoft Visual Basic 5.0 Learning Edition, Microsoft Visual Basic 5.0 Professional Edition, Microsoft Visual Basic 5.0 Enterprise Edition, Microsoft Visual Basic 4.0 Standard Edition, Microsoft Access 97 Standard Edition, Microsoft Excel 97 Standard Edition, Microsoft Excel 95 Standard Edition, Microsoft Word 97 Standard Edition