VB6으로 TCP/IP 통신 프로그램을 개발하다 보니
패킷 헤더 부분을 읽어서 바이트배열을 Integer 또는 Long 으로 변환해야될 일이 생깁니다.
VB6은 개발 경험이 별로 없다 보니 한참을 인터넷을 검색해보고 적절한 방법을 찾아냈네요.
Byte array to long, long to byte array 하는 펑션입니다.
'// '// Public Function BytesToLong(ByRef RefBytes() As Byte) As Long Dim lValue As Long Dim i As Integer On Error GoTo Errcheck For i = 0 To UBound(RefBytes) lValue = lValue + RefBytes(i) * (256 ^ (UBound(RefBytes) - i)) Next i BytesToLong = lValue Exit Function Errcheck: Dim sErr$ sErr = "BytesToLong" & Err.Number & Err.Description Debug.Print sErr End Function '// '// Public Function LongToBytes(ByVal lValue As Long) As Byte() Dim arBytes((LenB(lValue) - 1)) As Byte Dim i As Integer Dim lOutValue As Long On Error GoTo Errcheck lOutValue = lValue For i = 0 To (LenB(lOutValue) - 1) arBytes(i) = (Int(lOutValue / (2 ^ (8 * (LenB(lOutValue) - 1 - i))))) And ((2 ^ 8) - 1) Next i LongToBytes = arBytes Exit Function Errcheck: Dim sErr$ sErr = "LongToBytes" & Err.Number & Err.Description Debug.Print sErr End Function '// '//
실제 TCP/IP 통신시, 리틀엔디안, 빅엔디안에 따라 값이 다르게 나올 수 있는데
그때는 변환할 값에 대해 htonl 또는 nltoh 등의 Window API 함수를 선언해 적절하게 변환해서 사용하시면 됩니다.
Private Declare Function htonl Lib "WSOCK32.DLL" (ByVal hostlong As Long) As Long
Private Declare Function htons Lib "WSOCK32.DLL" (ByVal hostshort As Long) As Integer
Private Declare Function ntohl Lib "WSOCK32.DLL" (ByVal netlong As Long) As Long
Private Declare Function ntohs Lib "WSOCK32.DLL" (ByVal netshort As Long) As Integer
빅엔디안, 리틀엔디안 또는 바이트 오더링 관련해서는 API 함수와 인터넷을 참고하시기 바랍니다.
댓글