Posted By

jimfred on 08/15/09


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

umang_nine
khouser
danfinrud55


byte swapping using System.Net.IPAddress.NetworkToHostOrder


 / 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.

  1. using System.Diagnostics.Debug; // for Assert
  2. using System.Net.IPAddress; // for NetworkToHostOrder
  3.  
  4. Assert(0x12345678 == NetworkToHostOrder( 0x78563412)); // 4-byte
  5. Assert(0x12340000 == NetworkToHostOrder( 0x3412)); // 4-byte
  6. Assert(0x12000000 == NetworkToHostOrder( 0x12)); // 4-byte
  7. Assert( 0x1234 == NetworkToHostOrder((short)0x3412)); // 2-byte
  8. Assert( 0x1200 == NetworkToHostOrder( (short)0x12)); // 2-byte
  9.  
  10. Assert(0x123456789abcde10 == NetworkToHostOrder(0x10debc9a78563412)); // 8-byte
  11.  
  12. // using 'unchecked()' to convert large UInt32 values to negative Int32 values.
  13. // See stackoverflow.com/questions/1131843/how-do-i-convert-uint-to-int-in-c
  14. // In this usage it'ss like the reinterpret cast because bits remain unchanged.
  15. // Without unchecked, a runtime exception will be thrown
  16. // if the result becomes negative.
  17. Assert( 0xFF1234FF == (UInt32)NetworkToHostOrder(unchecked((Int32)0xFF3412FF)));

Report this snippet  

You need to login to post a comment.