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 'Create a long variable: lngMyNumber = 8675309 'Convert long to byte array: bytMyByteArray = LongToByteArray(lngMyNumber) 'Create output message: For lngIndx = lngLwrBnd_c To lngUprBnd_c strMsg = strMsg & (vbNewLine & Format$(bytMyByteArray(lngIndx), """bytMyByteArray(" & lngIndx & ")=""0")) Next 'Display output message: MsgBox "lngMyNumber converts to: " & strMsg 'Create byte array: ReDim bytMyByteArray(3) bytMyByteArray(0) = 237 bytMyByteArray(1) = 95 bytMyByteArray(2) = 132 bytMyByteArray(3) = 0 'Convert byte array to long: lngMyNumber = ByteArrayToLong(bytMyByteArray) 'Display output: MsgBox "bytMyByteArray converts to: " & lngMyNumber End Sub Public Function LongToByteArray(ByVal value As Long) As Byte() 'Purpose: Converts a variable of the type Long to a byte array. 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 'Purpose: Converts a byte array to variable of the type Long. 'Remarks, 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 'Arrays have to be passed by ref. Use tmp variable to prevent accidental 'alteration. bytTmp = value 'Prevent subscript errors If UBound(bytTmp) < lngUprBnd_c Then ReDim Preserve bytTmp(lngUprBnd_c) End If 'Load tmp array into ByteLong For lngIndx1 = lngLwrBnd_c To lngUprBnd_c blJump.value(lngIndx1) = bytTmp(lngIndx1) Next 'LSet syntax can only be used on User Defined Types: LSet tlJump = blJump ByteArrayToLong = tlJump.value End Function

How to use:

  1. Press Alt-F11 to open Visual Basic Editor
  2. From the "Insert Menu" select "Module" to insert a standard code module.
  3. In the newly created module, paste the code above.
  4. Run the procedure "ExampleUsage".
 

Test the code:

  1. Press Alt + F8
  2. Select the procedure "ExampleUsage"
  3. Click Run
 

Sample File:

vbaxkb_LongToByteAndBack.zip 8.59KB 

Approved by Zack Barresse


This entry has been viewed 37 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express