在VBA中将big-endian转换为little-endian,反之亦然

时间:2010-04-19 11:13:13

标签: vba excel-vba endianness excel

我的机器是little-endian(英特尔字节顺序)。我需要读取包含摩托罗拉/ IEEE字节顺序(“big-endian”)的16位有符号整数数据的二进制文件,然后进行一些计算,最后在big-endian二进制文件中写出生成的integer数据文件。

如何在VBA中执行上述操作,即将big-endian转换为little-endian,反之亦然?

原因是,我正在处理NASA Shuttle Radar Topography Mission数据(HGT file format)。

3 个答案:

答案 0 :(得分:2)

使用简单的按位逻辑。

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

嗯,由于VBA限制,并非如此简单。 不过,我相信这比调用CopyMemory函数要快两倍。

答案 1 :(得分:0)

这是一个可以帮助你入门的子程序:

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

答案 2 :(得分:0)

这是一个简单的ASCII转换:

Public Function SwapLong(Data As Long)As Long

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)

结束功能

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)

结束功能