I recently learned about endianness and am still having difficulty identifying problem areas.
Here is a snippet 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):
and so on.
If you isolate the conversion to the interface routines, the rest of your code becomes endian-agnostic.