Results 1 to 2 of 2

Thread: Swap Word UDF error while handling negative values

  1. #1

    Thread Starter
    New Member
    Join Date
    Nov 2019
    Posts
    15

    Swap Word UDF error while handling negative values

    The udf below outputs swapped long after WORD swap. It handles perfectly positives. How can it be modified to handle negative input? For es=xample, with n = +305419896 the output is 2018915346. But fails with n = -305419896.

    \
    Code:
    Public Function SwapWords( _
           ByRef n As Long) As Long
    
        Const m As Integer = 3
    
        Dim b(m) As Byte, i&, u$, v$
    
        u = VBA.Right("00000000" + VBA.Hex(n), 2& * (m + 1&))
        v = vbNullString
    
        For i = 0& To m
            v = v + VBA.Mid(u, (m - i) * 2& + 1&, 2&)
            b(i) = VBA.Mid(u, (m - i) * 2& + 1&, 2&)
        Next i
    
        SwapWords = CLng("&H" + v)
        Exit Function
    
    End Function

  2. #2
    PowerPoster
    Join Date
    Feb 2006
    Posts
    22,542

    Re: Swap Word UDF error while handling negative values

    You get the wrong results, the output should have been 1450709556. You also seem to think characters are bytes (they are not). All sorts of crazy is going on there.

    A couple of alternatives:

    Code:
    Private Declare Sub GetMem2 Lib "msvbvm60" (ByVal pSrc As Long, ByVal pDest As Long)
    
    Private Function SwapWords2(ByVal DWORD As Long) As Long
        Dim pDWORD As Long
        Dim pSwapWords2 As Long
    
        pDWORD = VarPtr(DWORD)
        pSwapWords2 = VarPtr(SwapWords2)
        GetMem2 pDWORD, (pSwapWords2 Xor &H80000000) + 2 Xor &H80000000
        GetMem2 (pDWORD Xor &H80000000) + 2 Xor &H80000000, pSwapWords2
    End Function
    
    Private Function SwapWords(ByVal DWORD As Long) As Long
        Dim LowWord As Long
        Dim HighWord As Long
    
        LowWord = DWORD And &HFFFF&
        If LowWord And &H8000& Then
            LowWord = (LowWord Xor &H8000&) * &H10000 Xor &H80000000
        Else
            LowWord = LowWord * &H10000
        End If
        HighWord = DWORD
        If HighWord And &H80000000 Then
            HighWord = (HighWord Xor &H80000000) \ &H10000 Xor &H8000&
        Else
            HighWord = HighWord \ &H10000
        End If
        SwapWords = LowWord Or HighWord
    End Function
    I'm sure others can think of several more approaches, and even clean up my SwapWords() function above.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width