VBA Tipp: Bytes vertauschen

Aus DBWiki
Wechseln zu: Navigation, Suche

Problem

Ich möchte die Bytes in einer ganzen Zahl (Long oder Integer) vertauschen.

Lösung

Das geht mit den folgenden Funktionen

Private Type LongType
  I As Long
End Type
Private Type IntType
  I As Integer
End Type
Private Type TwoBytes
  B(0 To 1) As Byte
End Type
Private Type FourBytes
  B(0 To 3) As Byte
End Type
 
Public Function intSwapBytes(I As Integer) As Integer
Dim IT As IntType, BT As TwoBytes, B As Byte
  IT.I = I
  LSet BT = IT
  B = BT.B(0)
  BT.B(0) = BT.B(1)
  BT.B(1) = B
  LSet IT = BT
  intSwapBytes = IT.I
End Function
 
Public Function lngSwapBytes(I As Long) As Long
Dim LT As LongType, BT As FourBytes, B As Byte
  LT.I = I
  LSet BT = LT
  B = BT.B(0)
  BT.B(0) = BT.B(3)
  BT.B(3) = B
  B = BT.B(1)
  BT.B(1) = BT.B(2)
  BT.B(2) = B
  LSet LT = BT
  lngSwapBytes = LT.I
End Function

Aufruf

Hex(lngSwapBytes(&HAABBCCDD))
'Rückgabe:
"DDCCBBAA"