/ Published in: C#
This shows how to implement simple byte swapping in C#.
It's shown in the context of assert statements instead of print statements to show the expected results.
Interesting post http://bytes.com/topic/c-sharp/answers/506861-littleendian-bigendian compared performance of various methods. mask-shift-or performed best.
It's shown in the context of assert statements instead of print statements to show the expected results.
Interesting post http://bytes.com/topic/c-sharp/answers/506861-littleendian-bigendian compared performance of various methods. mask-shift-or performed best.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
using System.Diagnostics.Debug; // for Assert using System.Net.IPAddress; // for NetworkToHostOrder Assert(0x12345678 == NetworkToHostOrder( 0x78563412)); // 4-byte Assert(0x12340000 == NetworkToHostOrder( 0x3412)); // 4-byte Assert(0x12000000 == NetworkToHostOrder( 0x12)); // 4-byte Assert( 0x1234 == NetworkToHostOrder((short)0x3412)); // 2-byte Assert( 0x1200 == NetworkToHostOrder( (short)0x12)); // 2-byte Assert(0x123456789abcde10 == NetworkToHostOrder(0x10debc9a78563412)); // 8-byte // using 'unchecked()' to convert large UInt32 values to negative Int32 values. // See stackoverflow.com/questions/1131843/how-do-i-convert-uint-to-int-in-c // In this usage it'ss like the reinterpret cast because bits remain unchanged. // Without unchecked, a runtime exception will be thrown // if the result becomes negative.