Adapt System.BitConverter to handle big endian (network) byte ordering in order to create number types from bytes and vice-versa


/ Published in: C#
Save to your folder(s)

The System.BitConverter class allows you to convert between bytes (in an array) and numerical types (int, uint, etc). However, it doesn't seem to let you set the endianness (which byte is most significant, e.g. in an int/Int32, there are four bytes, so which way do you read them?). It seems to operate such that the methods always return values appropriate to little endian (host order) systems (most significant byte is on the right). Since, in embedded systems, it is often necessary to interact with big-endian systems, I created this class to provide the functionality for either endianness. You simply set the endianness in the class, then all methods will return endian-aware values.

Please let me know if there is a better solution out there, as I searched a lot before deciding to do it this way. (Note: Instead of using LINQ [e.g. myArray.Reverse().ToArray()], you can use Array.Reverse(myArray).)

Found a bug in the previous code in that the arrays were being reversed, but the starting index was not, resulting in non-obvious behavior. I fixed that for all but the ToString methods.

URL: http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.