Converting big-endian to little-endian and vice versa in VBA

My machine is of little endian (Intel byte order). I need to read a binary file containing 16-bit signed integer data in Motorola / IEEE byte order ("big-endian"), then do some calculations, and finally write the resulting data integer

to the big-endian binary.

How to do it in VBA, i.e. convert big-endian to little-endian and vice versa?

The reason is that I am processing NASA's "Shuttle Spot Broadcast Mission" ( HGT file format ).

+2


a source to share


3 answers


Here is a subroutine that can get you started:



Public Sub ProcessData()
  Dim inputFileName As String
  Dim outputFileName As String
  Dim wordCount As Integer
  Dim i As Integer
  Dim msb As Byte
  Dim lsb As Byte
  Dim unsignedWord As Long
  Dim word As Integer

  inputFileName = "C:\Input.bin"
  outputFileName = "C:\Output.bin"

  wordCount = FileLen(inputFileName) / 2

  Open inputFileName For Binary Access Read As #1
  Open outputFileName For Binary Access Write As #2

  For i = 1 To wordCount
    Get #1, , msb
    Get #1, , lsb

    unsignedWord = CLng(msb) * 256 + lsb
    If unsignedWord > 32768 Then
      word = -CInt(65536 - unsignedWord)
    Else
      word = CInt(unsignedWord)
    End If

    ' Do something with each word.
    word = -word

    If word < 0 Then
      unsignedWord = 65536 + word
    Else
      unsignedWord = word
    End If
    msb = CByte(unsignedWord / 256)
    lsb = CByte(unsignedWord Mod 256)

    Put #2, , msb
    Put #2, , lsb
  Next

  Close #1
  Close #2
End Sub

      

0


a source


Using simple bitwise logic.

Public Function SwapBytes(ByVal i As Integer) As Integer
  Dim b1 As Byte, b2 As Byte

  b1 = i And &HFF

  If i And &H8000 Then
    b2 = ((i And &H7F00) / 256) Or &H80
  Else
    b2 = (i And &HFF00) / 256
  End If

  If b1 And &H80 Then
    SwapBytes = (b1 And &H7F) * 256 Or b2 Or &H8000
  Else
    SwapBytes = b1 * 256 Or b2
  End If

End Function

      



Well, not so easy due to VBA limitations. However, I believe it will be much faster than calling the CopyMemory function twice.

+2


a source


Here's a simple ASCII conversion:

Public Function SwapLong (data as long) length

Const Sz As Integer = 3
Dim Bytes(Sz) As Byte
Dim n As Integer
Dim HexStr As String
Dim SwpStr As String

HexStr = Right("00000000" + Hex(Data), 2 * (Sz + 1))
SwpStr = vbNullString

For n = 0 To Sz
    SwpStr = SwpStr + Mid(HexStr, (Sz - n) * 2 + 1, 2)
Next n

SwapLong = CLng("&h" + SwpStr)

      

End function

Public Function SwapInt (Data As Integer) As Integer

Const Sz As Integer = 1
Dim Bytes(Sz) As Byte
Dim n As Integer
Dim HexStr As String
Dim SwpStr As String

HexStr = Right("0000" + Hex(Data), 2 * (Sz + 1))
SwpStr = vbNullString

For n = 0 To Sz
    SwpStr = SwpStr + Mid(HexStr, (Sz - n) * 2 + 1, 2)
Next n

SwapInt = CInt("&h" + SwpStr)

      

End function

0


a source







All Articles