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

后端 未结 3 1140
借酒劲吻你
借酒劲吻你 2021-01-07 01:34

My machine is 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

3条回答
  •  误落风尘
    2021-01-07 02:32

    By 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 simple due to VBA limitations. Still, I believe that will be much faster than calling CopyMemory function twice.

提交回复
热议问题