What is the C equivalent for reinterpret_cast?

Solution 1:

int *foo;
float *bar;

// c++ style:
foo = reinterpret_cast< int * >(bar);

// c style:
foo = (int *)(bar);

Solution 2:

If you can take the address of the value, one way is to cast a pointer to it to a pointer to a different type, and then dereference the pointer.

For example, an float-to-int conversion:

int main()
{
  float f = 1.0f;

  printf ("f is %f\n", f);
  printf ("(int) f is %d\n", (int)f);
  printf ("f as an unsigned int:%x\n", *(unsigned int *)&f);
}

Output:

f is 1.000000
(int) f is 1
f as an unsigned int:3f800000

Note that this is probably not guaranteed to work by the C standard. You cannot use reinterpret_cast to cast from float to int anyway, but it would be similar for a type that was supported (for example, between different pointer types).

Let's confirm the output above makes sense, anyway.

http://en.wikipedia.org/wiki/Single_precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32

The last answer in binary:

0011 1111 1000 0000 0000 0000 0000 0000

This is IEEE-754 floating point format: a sign bit of 0, followed by an 8-bit exponent (011 1111 1), followed by a 23 bit mantissa (all zeroes).

To interpret the exponent, subtract 127: 01111111b = 127, and 127 - 127 = 0. The exponent is 0.

To interpret the mantissa, write it after 1 followed by a decimal point: 1.00000000000000000000000 (23 zeroes). This is 1 in decimal.

Hence the value represented by hex 3f800000 is 1 * 2^0 = 1, as we expected.

Solution 3:

C-style casts just look like type names in parenthesis:

void *p = NULL;
int i = (int)p; // now i is most likely 0

Obviously there are better uses for casts than this, but that's the basic syntax.

Solution 4:

It doesn't exist, because reinterpret_cast can not change [constness][3]. For example,

int main()
{
    const unsigned int d = 5;
    int *g=reinterpret_cast< int* >( &d );
    (void)g;
}

will produce the error:

dk.cpp: In function 'int main()':
dk.cpp:5:41: error: reinterpret_cast from type 'const unsigned int*' to type 'int*' casts away qualifiers