Click to See Complete Forum and Search --> : Byte Order


ncl
February 2nd, 2000, 09:22 AM
I need to convert little endian long integers(intel type) to Big Endian long integers (motorola type) - anybody any ideas - this basically involes switching the byte order of a 4 byte long ie. byte1-byte2-byte3-byte4 becomes 4-3-2-1.

I can do it if I write to a file as binary then read in as bytes then read out the bytes in reverse order, but this is a bit long-winded.

I need to be able to do it in a function.

TIA

Spectre
February 2nd, 2000, 10:15 AM
The problem here is that VB has no unsigned long datatype. All long integers in VB are signed. The solution is to create your own unsigned long type then copy the contents of a normal VB long into it (see below).


'Define your unsigned long
public Type UnsignedLong
B1 as Byte 'LoByte
B2 as Byte
B3 as Byte
B4 as Byte 'HiByte
End Type

'Define a usertype containing a VB long
public Type VBLong
Number as Long
End Type




Now you can set up your convertion function


public Function ConvertEndian(Original as Long) as Long
Dim Tmp as Byte
Dim TmpUnsigned as UnsignedLong
Dim OriginalNum as VBLong
OriginalNum = Original
LSet TmpUnsigned = OriginalNum
Tmp = TmpUnsigned.B1
TmpUnsigned.B1 = TmpUnsigned.B4
TmpUnsigned.B4 = Tmp
Tmp = TmpUnsigned.B2
TmpUnsigned.B2 = TmpUnsigned.B3
TmpUnsigned.B3 = Tmp
LSet OriginalNum = TmpUnsigned
ConvertEndian = OriginalNum.Number
End Function




We have just reversed the byte order of a VB Long.

ncl
February 4th, 2000, 02:44 AM
Excellent, thankyou.
BTW,

Line
OriginalNum = Original
Should read
OriginalNum.Number = Original

BrewGuru99
February 4th, 2000, 02:55 AM
Wait a sec, this is just swapping the bytes. Don't you have to swap all the bits within the bytes?

What you start with (two byte example instead of four byte):

Byte1 = 01.02.03.04.05.06.07.08
Byte2 = 09.10.11.12.13.14.15.16




Your conversion:

Byte1 = 09.10.11.12.13.14.15.16
Byte2 = 01.02.03.04.05.06.07.08




Isn't this what you want?:

Byte1 = 16.15.14.13.12.11.10.09
Byte2 = 08.07.06.05.04.03.02.01




Brewguru99