|
|
|
|
|
|
Multiple Apps
|
Convert Long to Byte Array without API Call
|
|
Ease of Use
|
Easy
|
Version tested with
|
2003
|
Submitted by:
|
Oorang
|
Description:
|
Convert a variable of the type "Long" to a Byte Array and back without using CopyMem.
|
Discussion:
|
When dealing with data and the byte level you may, on occasion need to covert a long into a byte array and vice-versa. One example of that might be to change endianness. Another might be just needing to write a long when using binary write.
|
Code:
|
instructions for use
|
Option Explicit
Private Type ByteLong
value(3) As Byte
End Type
Private Type TypedLong
value As Long
End Type
Public Sub ExampleUsage()
Const lngUprBnd_c As Long = 3
Const lngLwrBnd_c As Long = 0
Dim lngMyNumber As Long
Dim bytMyByteArray() As Byte
Dim strMsg As String
Dim lngIndx As Long
lngMyNumber = 8675309
bytMyByteArray = LongToByteArray(lngMyNumber)
For lngIndx = lngLwrBnd_c To lngUprBnd_c
strMsg = strMsg & (vbNewLine & Format$(bytMyByteArray(lngIndx), """bytMyByteArray(" & lngIndx & ")=""0"))
Next
MsgBox "lngMyNumber converts to: " & strMsg
ReDim bytMyByteArray(3)
bytMyByteArray(0) = 237
bytMyByteArray(1) = 95
bytMyByteArray(2) = 132
bytMyByteArray(3) = 0
lngMyNumber = ByteArrayToLong(bytMyByteArray)
MsgBox "bytMyByteArray converts to: " & lngMyNumber
End Sub
Public Function LongToByteArray(ByVal value As Long) As Byte()
Dim tlJump As TypedLong
Dim blJump As ByteLong
tlJump.value = value
LSet blJump = tlJump
LongToByteArray = blJump.value
End Function
Public Function ByteArrayToLong(ByRef value() As Byte) As Long
Const lngUprBnd_c As Long = 3
Const lngLwrBnd_c As Long = 0
Dim bytTmp() As Byte
Dim tlJump As TypedLong
Dim blJump As ByteLong
Dim lngIndx1 As Long
bytTmp = value
If UBound(bytTmp) < lngUprBnd_c Then
ReDim Preserve bytTmp(lngUprBnd_c)
End If
For lngIndx1 = lngLwrBnd_c To lngUprBnd_c
blJump.value(lngIndx1) = bytTmp(lngIndx1)
Next
LSet tlJump = blJump
ByteArrayToLong = tlJump.value
End Function
|
How to use:
|
- Press Alt-F11 to open Visual Basic Editor
- From the "Insert Menu" select "Module" to insert a standard code module.
- In the newly created module, paste the code above.
- Run the procedure "ExampleUsage".
|
Test the code:
|
- Press Alt + F8
- Select the procedure "ExampleUsage"
- Click Run
|
Sample File:
|
vbaxkb_LongToByteAndBack.zip 8.59KB
|
Approved by Zack Barresse
|
This entry has been viewed 37 times.
|
|