Thursday, July 5, 2012

Working with big endian data


A have always favored little endian number representation over big-endian, which why I was saddened whn I found that TCP/IP, and most internet protocols (such as SSL3) use a big endian representation for numbers. Following is the type of construct I use when I need to work with a non-native data type in structs that I pull off of the network.


 typedef unsigned char uint8; 
 struct uint16 
  {
     uint8 n[2];
     operator unsigned short()
         { return
            ((unsigned short)n[0] << 8) + n[1];
         }
 };



Using a struct like this has two advantages:
  • If a typedef unsigned short was used you could accidently use the number in situations without converting it. 
  • The operator unsigned short ensures that the struct can be used as a normal unsigned short where required

No comments:

Post a Comment