tags:

views:

114

answers:

4
+1  A: 

You could use memcpy:

#include <memory.h>
int main() {
    float f = 1.0;
    int n;
    memcpy( &n, &f, sizeof(f) );
}

I don't think there is an elegant solution to this, but whatever you do, I'd wrap it in a function to make it obvious what I was up to:

int FloatToInt( float f ) {
    int n;
    assert( sizeof(n) == sizeof(f) );
    memcpy( &n, &f, sizeof(f) );
    return n;
}
anon
+1 This is the safest way to do it. In theory using `reinterpret_cast` the way the OP does is undefined behaviour, although in practice it will probably work...
Andreas Brinck
I'd add `if ( sizeof float == sizeof int )`
Kirill V. Lyadvinsky
@Kirill I wouldn't, but I might add an assertion.
anon
Surely assertion is even better. Maybe some sort of `static_assert`...
Kirill V. Lyadvinsky
`WPARAM` is hardly a portable type. I don't think this case needs even an assertion. On Win32 and Win64, floats are no bigger than pointers, and it's entirely reasonable to assume the same for Win128.
MSalters
In this answer `FloatToInt` returns `int` and not `WPARAM`.
Kirill V. Lyadvinsky
+1  A: 

I would prefer the union. It is the clearest and easiest to understand. It also probably has the least amount of undefined behavior.

Gabe
Heh, nicely put: "least amount of undefined behaviour". :P
yngvedh
Using the union in this way (saving in one member and reading from another) evokes undefined behavior.
John Dibling
+1  A: 

Use reinterpret_cast< WPARAM &>(f). This cast is not restricted to pointers, it also works with references.

MSalters
Thanks! This was exactly what I was looking for.
yngvedh
A: 

I'd go the simple way of taking a pointer to your float, casting it to a pointer to UINT, and then dereferencing the resulting pointer:

WPARAM wParam = *((UINT*)(&f));

To convert it back you do the opposite. Doing the cast at pointer-level makes sure the compiler won't try any "conversion" behind your back.

float f = *((float*)(&wParam))
Koro