KugelnMMXVI KugelnMMXVI - 1 month ago 24
Objective-C Question

How to do a reinterpret_cast with Obj-C?

Edit: I am looking for

in Objective-C so the following is meaningless for my intended question.

Are there static casts in Objective-C?

e.g. in this C++ example
is used for a good reason:

float rnd = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

I can think of using a
or pointers to directly access the
integer value as a float but that would make the code much more

How would I do the same thing as in the C++ example conveniently in


After the clarification you are after reinterpret_cast:

You are correct you can do it with a union. If you want to do it inline you can use a cast, address-of and indirection...

The C-style cast (type)expr in both (Objective-)C and C++ works similarly: if the equivalent of a static_cast is appropriate it does that, e.g. between int and float and other value types; otherwise it will do the equivalent of a reinterpret_cast, e.g. between pointer-types.

So you just need to convert to a pointer, cast, and indirect. E.g.:

int z = 0xDEADBEEF;
float y = *(float *)&z;
NSLog(@"%d -> %f", z, y);

Yes it's a bit ugly, but then what you are doing is as well ;-) To make it a bit nicer define it as a macro:

#define REINTERPRET(type, expr) (*(type *)&(expr))

which you can use as:

int z = 0xDEADBEEF;
float y = REINTERPRET(float, z);
NSLog(@"%d -> %f", z, y);

As with reinterpret_cast, you should use this sparingly and with care!