On 09/05/2009 03:05 AM, Ed Boas wrote:
The following code: ---------- #include<stdio.h> #include<inttypes.h> // Rounds in current rounding mode, which is "round to closest integer" by default on Pentium& Xeon // Valid for |fval|<= 2^22 - 1, that is, -4194303<= fval<= 4914303 // based on code from www.lomont.org inline int32_t fast_round(float x) { x+=12582912; // 2^23+2^22 int32_t i=*(int32_t*)&x; i&=8388607; // 2^23-1; i-=4194304; // 2^22 return i; } int main(void) { printf("%f rounds to %i\n", 1.4f, fast_round(1.4f)); return 0; } [...] However, when it is compiled with g++ -O2, it prints: 1.400000 rounds to -4194304 [...]
Your code is not correct C++. Please read: http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html