What happens when float pointer is typecasted to char pointer?

前端 未结 6 1415
后悔当初
后悔当初 2020-12-12 04:09
int main()
{
    float f = 12.2;
    char *p1;
    p1 = (char *)&f;
    printf (\"%d\", *p1);
}

This outputs 51.

6条回答
  •  盖世英雄少女心
    2020-12-12 05:01

    You can cast a float* to a char* just fine, it's the using of such a beast that may be problematic.

    When you de-reference it, you'll simply get the char representation of the first part (but see below to understand what this really means, it's not as clear as you may think) of the float.

    If you're talking about IEE754 floats, 12.2 in IEEE754 float is (abcd are the octets):

    S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM (sign, exponent, mantissa).
    0 10000010 10000110011001100110011
    a aaaaaaab bbbbbbbccccccccffffdffffffffd
    

    The 00110011 at the end is the 51 (0x33) that you're seeing. The reason you're seeing the last bit of the float is because it's stored like this in memory (in a little-endian architecture):

    00110011 00110011 01000011 01000001
    ffffdffffffffd cccccccc bbbbbbbb aaaaaaaa
    

    which means that the char* cast of the float* will point at the ffffdffffffffd part.

    On big-endian architectures, you would get the aaaaaaaa bit, 01000001, or 65 (0x41).

提交回复
热议问题