<strong>Edit:</strong> I am looking for
reinterpret_castin Objective-C so the following is meaningless for my intended question.
Are there static casts in Objective-C?
e.g. in this C++ example
static_cast is used for a good reason:
float rnd = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
I can think of using a
union 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 Objective-C?</blockquote> Answer1:
After the clarification you are after
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
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);
reinterpret_cast, you should use this sparingly and with care!
Objective C is a superset of C so do this the C way and simple casts
float rnd = (float) (rand()) / (float)(RAND_MAX);