3

I am having trouble converting from a Byte Array to a Signed Integer in VB6. This would be simple to do with BitConverter in .NET but I'm not sure what to do with VB6. Thanks

3 Answers 3

2

Unfortunately no built in function, you need to write one. Here is a quick sample to get you started.

Private Function BArrayToInt(ByRef bArray() As Byte) As Integer
    Dim iReturn As Integer
    Dim i As Integer

    For i = 0 To UBound(bArray) - LBound(bArray)
        iReturn = iReturn + bArray(i) * 2 ^ i
    Next i

    BArrayToInt = iReturn

End Function
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this only converts a single 4 byte array into a single Long value.
1

CopyMemory

Air code (may crash your PC, cause dinosaur attack, etc).

Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As Any, _ source As Any, ByVal bytes As Long)  

Dim a() As Byte 
Dim n As Integer 
 'get the bytes somehow into a()
CopyMemory n, a(0), 2 

Comments

0

I know this is OLD but people like me still find it useful to get me pointed in the right direction.

@jac solution did not work for me but I came up with a mod to his code that solved a limitation of it that would not convert the result which which was still inside the negative bounds of a LONG. That is hard to explain but here is the clumsy code that solves that limitation:

Function BArrayToSignedLong(ByRef bArray() As Byte) As Long
 'NOTE: bArray can now be UNSIGNED if your final result is in +/- 2^31 range of a LONG
 Dim twoTo32 As Currency 'just temporary to handle intermediate results outside of LONG limits
 Dim cReturn As Currency 'this is 64 bits than can handle going over 2^32
 Dim iReturn As Long  'this is signed 32 bit to send back
 Dim i As Integer
 twoTo32 = 2 ^ 32 'make this next up or down count loop direction based on the endian order you need
 For i = 0 To UBound(bArray) - LBound(bArray)
    cReturn = cReturn + (bArray(i) * (256 ^ i))
 Next i
 If cReturn > twoTo32 / 2 Then
     cReturn = cReturn - twoTo32
 End If
 iReturn = cReturn 'take Currency value back to a LONG variable
 BArrayToSignedLong = iReturn
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.