Monday, January 14, 2008

Type Casting between Basic Types

We have a double type variable and need to pass it to another module. However, we only have a communication API that can pass a single uint32_t. How can we do this without losing any precision?

Using the following C style casting is not working:

double d = 3.14;
int i = (int) d;

In this case i = 3 and we lost the decimals.

Using C++ style static_cast has the same effect:

int i = static_cast(d);

The C++ reinterpret_cast seems to work how ever if you write

int i = reinterpret_cast(d);


it is not working. reinterpret_cast can only cast between pointer types.

So, we got the hint here: reinterpret it as a pointer!

The correct solution then works as this way:

nt i = *(reinterpret_cat<*int>(&d));

If you prefer the C style, this could be neater:

int i = *((int *)(&d));

When we need to decode it, simple do the reverse way:

double newD = *((double *)(&i));

No comments: