CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Byte Order

  1. #1
    Join Date
    Jan 2000
    Posts
    8

    Byte Order

    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


  2. #2
    Join Date
    Feb 2000
    Posts
    137

    Re: Byte Order

    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.


  3. #3
    Join Date
    Jan 2000
    Posts
    8

    Re: Byte Order

    Excellent, thankyou.
    BTW,

    Line
    OriginalNum = Original
    Should read
    OriginalNum.Number = Original



  4. #4
    Join Date
    Oct 1999
    Location
    CA
    Posts
    91

    Re: Byte Order

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured