How to Byte-Swap a Float
Here is a way I found to do a byte swap on a floating point number. For those who dont know what that is, it is a method that I use for converting data so that machines with different architectures can share data. Intel machines, for example, are "little endian", whereas Sun boxed are "big endian". Anyone else have another way to do the same thing? Keep reading for my method...
Here it is:
-
floatSwp(float f){
-
union{ float f;
-
char b[4];
-
}dat1, dat2;
-
dat1.f = f;
-
dat2.b[0] = dat1.b[3];
-
dat2.b[1] = dat1.b[2];
-
dat2.b[2] = dat1.b[1];
-
dat2.b[3] = dat1.b[0];
-
return dat2.f;
-
}
Update: This will not always work properly! I found this code (I believe) in the open-source Quake code. To see how it fails, construct a loop that swaps a counter value twice - once to big endian, for example, and then back. Compare the counter value with the swapped value, and it will not always be equal. Why is this, anyone care to explain?
My guess is a bit is being lost somewhere.... but I haven't been able to figure it out. Therefore, its an EXTREMELY bad idea to use this for byte swapping - I am surprised that whoever coded this conversion got away with it.