Game Engine Architecture

(Ben Green) #1
107


  1. You can have your tools endian-swap the data prior to writing it into a
    binary data fi le. In eff ect, you make sure that the data fi le uses the endi-
    anness of the target microprocessor (the game console), even if the tools
    are running on a machine that uses the opposite endianness.


Integer Endian-Swapping


Endian-swapping an integer is not conceptually diffi cult. You simply start at
the most signifi cant byte of the value and swap it with the least signifi cant
byte; you continue this process until you reach the half-way point in the value.
For example, 0xA7891023 would become 0x231089A7.
The only tricky part is knowing which bytes to swap. Let’s say you’re writ-
ing the contents of a C struct or C++ class from memory out to a fi le. To
properly endian-swap this data, you need to keep track of the locations and
sizes of each data member in the struct and swap each one appropriately
based on its size. For example, the structure


struct Example
{
U32 m_a;
U16 m_b;
U32 m_c;
};

might be writt en out to a data fi le as follows:


void writeExampleStruct(Example& ex, Stream& stream)
{
stream.writeU32(swapU32(ex.m_a));
stream.writeU16(swapU16(ex.m_b));
stream.writeU32(swapU32(ex.m_c));
}

and the swap functions might be defi ned like this:


inline U16 swapU16(U16 value)
{
return ((value & 0x00FF) << 8)
| ((value & 0xFF00) >> 8);
}

inline U32 swapU32(U32 value)
{
return ((value & 0x000000FF) << 24)
| ((value & 0x0000FF00) << 8)
| ((value & 0x00FF0000) >> 8)
| ((value & 0xFF000000) >> 24);
}

3.2. Data, Code, and Memory in C/C++

Free download pdf