Keep in mind a few things in my code were done due to verbosity (implicit casts made explicit) due to my belief it's a good thing to do. I need to clean some stuff up (like the templates on the integral type is unnecessary) and the memory leak.
I tested this against ID software's version which I happened to find on Gamedev in an article.
In any case I needed endian independence and this is my result.
This was tested against ID's code and it always gave the same results as theirs.
Now I wait for someone to bite my head off. If there's reason to do so then go right ahead.
I tested this against ID software's version which I happened to find on Gamedev in an article.
In any case I needed endian independence and this is my result.
This was tested against ID's code and it always gave the same results as theirs.
Now I wait for someone to bite my head off. If there's reason to do so then go right ahead.
Code:
class EndianFloatSwap
{
public:
float SwapFloat(const float &value){
void *floatingBite = static_cast<void*>(const_cast<float*>(&value));
unsigned char arrayBytes[sizeof(float)];
unsigned char *floatAsByte = 0x00;
floatAsByte = (reinterpret_cast<unsigned char*>(floatingBite));
SwapByteOrder(floatAsByte, arrayBytes, sizeof(float));
return *reinterpret_cast<float*>(arrayBytes);
}
double SwapDouble(const double &value){
void *floatingBite = static_cast<void*>(const_cast<double*>(&value));
unsigned char arrayBytes[sizeof(double)];
unsigned char *floatAsByte = 0x00;
floatAsByte = (reinterpret_cast<unsigned char*>(floatingBite));
SwapByteOrder(floatAsByte, arrayBytes, sizeof(double));
return *reinterpret_cast<double*>(arrayBytes);
}
private:
void SwapByteOrder(unsigned char *byteConvertedFloat, unsigned char arrayBytes[], const unsigned int &numberOfBytePairs){
const unsigned int bytesInPointerMinus1 = numberOfBytePairs - 1;
for(unsigned int idx=0; idx < numberOfBytePairs; idx++){
arrayBytes[idx] = byteConvertedFloat[bytesInPointerMinus1 - idx];
}
}
};
template <typename T>
class EndianIntegralSwap
{
public:
short SwapShort(const short &value){
return this->IntegralSwap(value);
}
int SwapInt(const int &value){
return this->IntegralSwap(value);
}
private:
T IntegralSwap(const T &value){
const unsigned int maxSize = sizeof(T);
const unsigned int bitsPerByte = 8;
const T mask = 0xFF;
unsigned char mod = 0;
unsigned char reverseMod = 0;
T result = 0;
mod = 0;
reverseMod = bitsPerByte * (maxSize - 1);
result = ((value >> mod) & mask) << reverseMod;
for(unsigned int idx=1; idx < maxSize; idx++){
mod = idx * bitsPerByte;
reverseMod = bitsPerByte << idx;
result |= static_cast<T>(((value >> mod) & mask) << reverseMod);
}
return result;
}
};