Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short pointer to a float

Tags:

c++

i run this code in c++:

#include <iostream>
using namespace std;
int main()
{
    float f = 7.0;
    short s = *(short *)&f;
    cout << sizeof(float) << endl
         << sizeof(short) << endl
         << s << endl;
    return 0;
}

i get the following out pot:

4
2
0

but, in a lecture given in Stanford university, Professor Jerry Cain says he is sure the out pot well not be 0.

the lecture is can be fond here. he says that around the 48 minute.

is he wrong, or that some standard change since? or is there a difference between platforms?
I'm using g++ to compile my code.

EDIT: in the next lecture he does mention "big endian" and "small endian" and says that they well affect the result.

like image 256
elyashiv Avatar asked Sep 22 '26 11:09

elyashiv


2 Answers

static void bitPrint(float f)
{
    assert(sizeof(int) == sizeof(float));
    int *data = reinterpret_cast<int*>(&f);
    for (int i = 0; i < sizeof(int) * 8; ++i)
    {
        int bit = (1 << i) & *data;
        if (bit) bit = 1;
        cout << bit;
    }
    cout << endl;
}

int main()
{
    float f = 7.0;
    bitPrint(f);
    return 0;
}

This program prints 00000000000000000000011100000010

Since the sizeof(short) == 2 on your platform you get the first 2 bytes which are both zeros

Note that since size of types and possibly float implementation (not sure about this) are implementation defined different output can be seen on different platforms.

like image 141
Andrew Avatar answered Sep 25 '26 02:09

Andrew


Well, let's see. First you write a float into the memory. It occupies 4 bytes, and it's value is 7. A float in the memory looks something like "sign bit -> exponent bits -> mantissa bits". I'm not sure how many bits are there for each part exactly, probably that depends on your platform.

Since the float's value is 7, it only occupies some of the least-significant bits on the right (I assume big-endian).

Your short pointer points to the beginning of the float, which means to the most significant bit. Since the value is greater than 0, the sign bit is zero. Since the float value is far on the right, we can say that those two most significant bytes are filled with zeros.

Now, provided that a size of short is 2, which means we will only take two bytes out of float's 4 bytes, we get our 0.

I believe though, that this result is rather UB and can differ on different platforms, compilers, etc.

like image 41
SingerOfTheFall Avatar answered Sep 25 '26 02:09

SingerOfTheFall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!