MathGem:Endian Operations

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

These functions deal with converting endianness. For more information on endianess, take a look at Wikipedia's article on Endianness.


Contents

Convert a WORD

This macro will flip the bytes within a WORD (2 Byte) value to convert between little endian and big endian format.

C/C++

You can also use htons() and ntohs() to convert between host and network byte order. On Linux these functions can be found in netinet/in.h and on Windows they are a part of Winsock2 and can be found in Winsock2.h.

#define FlipWord(w) ( (w)<<8 | (w)>>8 ) 

Python

You can also use htons() and ntohs() to convert between host and network byte order. These functions are found in the socket module.

def FlipWord(w):
    return ((w << 8) & 0x0FF00) | (w >> 8)

Convert a DWORD

This macro will flip the bytes within a DWORD (4 byte) value to convert between little endian and big endian format.

C/C++

You can also use htonl() and ntohl() to convert between host and network byte order. On Linux these functions can be found in netinet/in.h and on Windows they are a part of Winsock2 and can be found in Winsock2.h.

#define FlipDword(d) ((d)<<24 | (((d)<<8) & 0x00FF0000) | (((d)>>8) & 0x0000FF00) | (d)>>24) 

Python

You can also use htonl() and ntohl() to convert between host and network byte order. These functions are found in the socket module.

def FlipDword(d):
    return (((d)<<24) & 0xFF000000) | (((d)<<8) & 0x00FF0000) | (((d)>>8) & 0x0000FF00) | (d)>>24)