Search code examples
c++reinterpret-cast

C++ : int* / float* to char*, why get different result using reinterpret_cast?


  • int* to char* :

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

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

  • float* to char* :

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

Result : pChar[0] = 'a';

So why I'm getting two different results ?

Thanks for your help.


Solution

  • Both float and int are data types which are (usually) represented by four bytes:

    b1 b2 b3 b4
    

    However, those bytes are interpreted quite differently across the two types - if they wouldn't, there would be hardly any need for two types.

    Now if you reinterpret the pointers to pointers-to-char, the result points only to the first byte, as this is the length of a char:

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

    As said, this first byte has a very different meaning for the two data types, and this is why the representation as a char in general differs.


    Application to your example:

    The number 57 in float (IEEE754 Single precision 32-bit) is represented in bits as

    01000010 01100100 00000000 00000000
    

    In contrast, the representation in a 32-bit integer format is

    00000000 00000000 00000000 00111001
    

    Here the number seems to be represented in "big-endian" format, where the most important byte (the one which changes the value of the int the most) comes first. As mentioned by @Jean-FrançoisFabre, in your PC it seems to be the other way round, but nevermind. For both conversions, I used this site.

    Now your char* pointers point to the first of those 8-bit-blocks, respectively. And obviously they're different.