arranging 4 bytes into Long data type

rolex

New member
Local time
Today, 13:26
Joined
Aug 18, 2002
Messages
7
Suppose I have 4 separate bytes that i need to arrange in a
single variable of Long data type (IP address, to be specific)

I don't care about sign, just need to put bit data into a variable of
4 bytes size.

This seemed like a trivial thing to me, but the function below
generates Overflow.

Code:
Private Function toLong(ByVal n1 As Long, ByVal n2 As Long, 
ByVal n3 As Long, ByVal n4 As Long) As Long 

toLong = (n1 * (CLng(&H100) ^ 3)) Or (n2 * (CLng(&H100) ^ 2)) 
Or (n3 * CLng(&H100)) Or CLng(n4) 

End Function

Furthermore, I tried to use Currency data type, and surprisingly,
still getting Overflow error.

Code:
Private Function toLong(ByVal n1 As Currency, ByVal n2 As 
Currency, ByVal n3 As Currency, ByVal n4 As Currency) As Currency 

toLong = (n1 * (CCur(&H100) ^ 3)) Or (n2 * (CCur(&H100) ^ 2)) 
Or (n3 * CCur(&H100)) Or CCur(n4) 

End Function

Is there any way to just shift bits in a Long? I can do it easily in
C/C++, but don't know about VB
 
Or is a relational operator and is used in conditional statements. What are you trying to do with it in this calculation?
 
Use an API function for best results...

Code:
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
    (Destination As Any, Source As Any, ByVal Length As Long)

Public Function toLong(ByVal n1 As Byte, ByVal n2 As Byte, _
    ByVal n3 As Byte, ByVal n4 As Byte) As Long
  Dim b(0 To 3) As Byte
  b(0) = n4
  b(1) = n3
  b(2) = n2
  b(3) = n1
  CopyMemory toLong, b(0), 4
End Function
 
Just in case you don't like using API functions, here's a pure VB way of doing it (probably nowhere near as efficient)...

Code:
Public Function toLong2(ByVal n1 As Byte, ByVal n2 As Byte, _
    ByVal n3 As Byte, ByVal n4 As Byte) As Long
  toLong2 = Val("&H" & Right$("0" & Hex(n1), 2) _
                     & Right$("0" & Hex(n2), 2) _
                     & Right$("0" & Hex(n3), 2) _
                     & Right$("0" & Hex(n4), 2) & "&")
End Function
 

Users who are viewing this thread

Back
Top Bottom