What is the C equivalent for reinterpret_cast?

后端 未结 3 2101
[愿得一人]
[愿得一人] 2021-02-11 13:20

What is the C equivalent for the reinterpret_cast from C++?

相关标签:
3条回答
  • 2021-02-11 13:55

    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.

    0 讨论(0)
  • 2021-02-11 14:18
    int *foo;
    float *bar;
    
    // c++ style:
    foo = reinterpret_cast< int * >(bar);
    
    // c style:
    foo = (int *)(bar);
    
    0 讨论(0)
  • 2021-02-11 14:20

    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.

    0 讨论(0)
提交回复
热议问题