Results 1 to 5 of 5

Thread: Endians strike back

  1. #1

    Thread Starter
    vbuggy krtxmrtz's Avatar
    Join Date
    May 2002
    Location
    In a probability cloud
    Posts
    5,573

    Endians strike back

    Does someone have an code example on how to convert from big to little endian?

    Yes, I know this issue has been coming up repeatedly but I haven't found a satisfactory answer by searching the forums.

  2. #2
    Frenzied Member
    Join Date
    Aug 2000
    Location
    O!
    Posts
    1,177
    Use the API routines:
    ntohs - network to host short
    htons - host to network short
    ntohl - network to host long
    htonl - host to network long

    VB Code:
    1. Public Declare Function htons Lib "ws2_32.dll" (ByVal hostshort As Integer) As Integer
    2. Public Declare Function htonl Lib "ws2_32.dll" (ByVal hostlong As Long) As Long
    3. Public Declare Function ntohs Lib "ws2_32.dll" (ByVal netshort As Integer) As Integer
    4. Public Declare Function ntohl Lib "ws2_32.dll" (ByVal netlong As Long) As Long
    To be specific, you want to use the ntoh_ to get the little-endian format.
    Last edited by ccoder; Oct 20th, 2003 at 08:37 AM.

  3. #3

    Thread Starter
    vbuggy krtxmrtz's Avatar
    Join Date
    May 2002
    Location
    In a probability cloud
    Posts
    5,573
    I've written a simple test code and it works nicely. However I don't really understand the differences between ntohs and htons, apparently they both switch the byte order. The other 2 functions I haven't found any documentation about.

    Thanks for the help.

  4. #4

  5. #5
    Frenzied Member
    Join Date
    Aug 2000
    Location
    O!
    Posts
    1,177
    To tell you the truth, I have never looked to see if they do anything more than swap the byte order. If they don't, then you should be able to get by with one routine - call it once to swap the byte order and call it again to put the bytes back in their original order. My guess it that there is more to the routines than the obvious.

    To be safe, put the integers & longs in network-byte order (big-endian) and let the other side handle what you send as needed. In my environment, the systems that I send data to are big-endian, so they really don't have to do anything with the data before using it.

    htonl and ntohl, as stated in my earlier post, are for Longs. They are identical to htons and ntohs except that they handle 32 bit values rather than 16 bit values.

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