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.
Printable View
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.
Use the API routines:
ntohs - network to host short
htons - host to network short
ntohl - network to host long
htonl - host to network long
To be specific, you want to use the ntoh_ to get the little-endian format.VB Code:
Public Declare Function htons Lib "ws2_32.dll" (ByVal hostshort As Integer) As Integer Public Declare Function htonl Lib "ws2_32.dll" (ByVal hostlong As Long) As Long Public Declare Function ntohs Lib "ws2_32.dll" (ByVal netshort As Integer) As Integer Public Declare Function ntohl Lib "ws2_32.dll" (ByVal netlong As Long) As Long
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.
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.