Lilliput and Files: An Aventure in Endianess Issues
Background
In Jonathan Swift’s Gulliver’s Travels, the main character, Gulliver, arrives in a land of little people (called Lilliput). Here he encounters two warring factions — those that cut eggs from the little end first, and those who cut eggs from the big end first. Thus the Little-Endians and Big-Endians warred over something fairly unimportant.
Similarly, in the land of computing, there are two major factions of how to store datatypes in memory and on disk. They are also called Little-Endian (least significant first) and Big-Endian (most significant first). Please note that there are other factions. In school (and other places) we tend to learn to use binary and hexadecimal notation in Big-Endian format (where the right most digit is the ‘ones’ column).
So What?
Generally speaking, Intel and AMD processors are Little-Endian, while IMB/Motorola and PowerPC are Big-Endian. So when they store an integer (and other datatypes) in memory or on disk, they store the bytes in a particular order. If you transfer this file (that you wrote) to the other Endian processor and try to read the integer it will not be the “same” integer! What you have to do is reverse the order of the bytes in order to get this to work. This problem is also found on transfering things over a network. Generally speaking, networks speak in Big-Endian format.
Example:
Decimal: 16909060
Big-Endian Hex: 01 02 03 04
Big-Endian Binary: 00000001 00000010 00000011 00000100
Little-Endian Hex: 04 03 02 01
Little-Endian Binary: 00000100 00000011 00000010 00000001
.Net Method of Converting
Using System.Net.IPAddress.NetworkToHostOrder() you can convert from Big-Endian to whatever the current system Endianess is.
see: IPAddress.NetworkToHostOrder Method at msnd.microsoft.com.
Similarly, System.Net.IPAddress.HostToNetworkOrder() will convert from the current system Endianess to Big-Endian.
see:
IPAddress.HostToNetworkOrder Method as msdn.microsoft.com.
Other Solution
If you have to roll your own solution, be sure to test what type of system you are on by creating a byte array (or similar), copying those bits into an integer and compare to what you know the integer is supposed to be (easiest in Big-Endian). If it’s different, you know you’re in non-Big-Endian. Likely you are in Little-Endian, but you may be in a different Endian as well.
see:
Endianness on Wikipedia.org.
Tags: .NET, big endian, code, endian, literary, little endian
Comments
Leave a Reply
You must be logged in to post a comment.