【问题标题】:C++ : int* / float* to char*, why get different result using reinterpret_cast?C++:int* / float* 到 char*,为什么使用 reinterpret_cast 得到不同的结果?
【发布时间】:2017-02-21 09:54:50
【问题描述】:
  • int*char*

    int* pNum = new int[1];
    pNum[0] = 57;
    char* pChar = reinterpret_cast< char* >(pNum);

    结果:pChar[0] = '9'; //'9' ASCII 57

  • float*char*

    float* pFloat = new float[1];
    pFloat[0] = 57; //assign the same value as before
    char* pChar = reinterpret_cast< char* >(pFloat);

结果:pChar[0] = 'a';

那么为什么我会得到两个不同的结果?

感谢您的帮助。

【问题讨论】:

  • 因为floatint 的含义不同

标签: c++ reinterpret-cast


【解决方案1】:

你有这个是因为浮点值不使用与整数值相同的编码(IEEE编码与尾数+指数或类似的东西)

另外,我想你正在运行一个小端 CPU,否则你的第一个测试会产生 0(我的意思是 '\0')。

【讨论】:

    【解决方案2】:

    floatint 都是(通常)由四个字节表示的数据类型:

    b1 b2 b3 b4
    

    但是,这些字节在这两种类型中的解释完全不同 - 如果不这样,则几乎不需要两种类型。

    现在如果你重新解释指向字符指针的指针,结果只指向第一个字节,因为这是char 的长度:

    b1 b2 b3 b4
    ^^
    your char* points to here
    

    如前所述,第一个字节对于两种数据类型的含义非常不同,这就是为什么 char 的表示通常不同的原因。


    应用到您的示例:

    浮点数(IEEE754 单精度 32 位)中的数字 57 以位表示为

    01000010 01100100 00000000 00000000
    

    相比之下,32位整数格式的表示是

    00000000 00000000 00000000 00111001
    

    这里的数字似乎以“大端”格式表示,其中最重要的字节(改变 int 值最大的字节)排在第一位。正如@Jean-FrançoisFabre 所提到的,在您的 PC 中,它似乎是相反的,但没关系。对于这两种转换,我都使用了this site

    现在您的 char* 指针分别指向这些 8 位块中的第一个。显然它们是不同的。

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2015-04-06
      • 2018-09-06
      • 2012-11-27
      • 2015-01-19
      • 1970-01-01
      相关资源
      最近更新 更多