I recently learned about endianness and am still having difficulty identifying problem areas.
Here is a snipp开发者_如何学JAVAet of code that uses data loaded from a binary file (a Dxt texture). I am uncertain if endianness could cause problems in this situation, such as the width, height, and the hexadecimal comparison. What things do I need to change and why?
DxtHeader* header = (DxtHeader*)data;
width = header->width;
height = header->height;
uint pixelFormat = header->pixelFormat.fourCC;
if (pixelFormat == 0x31545844){
...
} else if (pixelFormat == 0x33545844){
...
} else if (pixelFormat == 0x35545844){
...
}
Generally speaking, endianness only matters if your data is travelling over some physical interface (e.g. across a network, or to a file), where it may have originated from a platform with a different native endianness. It also occurs if you're trying to do "clever" things with pointer casts, e.g. int a = 0xABCD; char b = *(char *)&a;
.
It's not clear from your example where the original data comes from, but I assume that it's been read from a file or somewhere. Really, the best place to deal with endianness conversion is as close to the interface as possible, so in your case, the routine that reads the file and fills the structure. Typically, this can be solved with preprocessor #ifdefs, e.g. in C (I know this is a C++ question, but I'm sure you can find an appropriate equivalent):
#ifdef (LITTLE_ENDIAN)
#define FILE_TO_NATIVE_16(x) ((((x) & 0xFF) << 8) | ((x) >> 8))
#else
#define FILE_TO_NATIVE_16(x) (x)
#endif
and so on.
If you isolate the conversion to the interface routines, the rest of your code becomes endian-agnostic.
It's probably best to save out the data in the first place appropriate to the target platform. I.e. when you create the data files, endian swap all of the fields.
That point aside, I would think that your DXT loader should handle this automatically, since DXTs are generally going to be built on Windows machines which are little endian these days.
精彩评论