reinterpret_cast的C等价物是多少?

时间:2009-09-05 00:24:06

标签: c

来自C ++的reinterpret_cast的C等价物是什么?

7 个答案:

答案 0 :(得分:30)

int *foo;
float *bar;

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

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

答案 1 :(得分:4)

C样式的强制转换看起来像括号中的类型名称:

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

显然,演员阵容的用途比这更好,但这是基本语法。

答案 2 :(得分:3)

它不存在,因为reinterpret_cast不能改变[constness] [3]。例如,

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

会产生错误:

  

dk.cpp:在函数'int main()'中:
     dk.cpp:5:41:错误:从'const unsigned int *'类型的reinterpret_cast到类型'int *'强制转换限定符

答案 3 :(得分:2)

如果你可以获取值的地址,一种方法是将指针转换为指向不同类型的指针,然后取消引用指针。

例如,float-to-int转换:

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);
}

输出:

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

请注意,这可能无法保证符合C标准。无论如何,你不能使用reinterpret_cast从float转换为int,但对于支持的类型(例如,在不同的指针类型之间)它将类似。

无论如何,让我们确认上面的输出是有道理的。

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

二进制的最后一个答案:

0011 1111 1000 0000 0000 0000 0000 0000

这是IEEE-754浮点格式:符号位为0,后跟8位指数(011 1111 1),后跟23位尾数(全零)。

要解释指数,减去127:01111111b = 127,127 - 127 = 0.指数为0.

要解释尾数,请在1后跟小数点后写入:1.00000000000000000000000(23个零)。这是十进制的1。

因此,正如我们所料,十六进制3f800000所代表的值是1 * 2 ^ 0 = 1。

答案 4 :(得分:1)

C风格的演员是:

int* two = ...;
pointerToOne* one = (pointerToOne*)two;

答案 5 :(得分:1)

c:{/ p>的REINTERPRET运算符怎么样?

#define REINTERPRET(new_type, var) ( * ( (new_type *)   & var ) )

我不喜欢说“reinterpret_cast”,因为演员意味着转换(在c中), 而重新解释意味着相反:没有转换。

答案 6 :(得分:0)

您可以像在任何其他类型中一样自由地在C中投射指针类型。

完成:

void *foo;
some_custom_t *bar;
other_custom_t *baz;
/* Initialization... */
foo = (void *)bar;
bar = (some_custom_t *)baz;
baz = (other_custom_t *)foo;
相关问题