Ebrahim Ghasemi
Ebrahim Ghasemi

Reputation: 6116

Interpret a 4 byte int as a 4 byte float

Look at this simple program :

#include <iostream>
using namespace std;

int main()
{
unsigned int i=0x3f800000;
float* p=(float*)(&i);
float f=*p;
cout<<f;
}

This is what I expect from the program:

  1. Last line: we must see f in output.
  2. Previous: f is the value that p is point to.
  3. Previous: p points to the value that is in the address of variable named i. (i.e. to the value of i)
  4. i is 0x3f800000

So I expect to see the 0x3f800000in output, but It prints 1 instead. Why?

ap1019@sharifvm:~$ ./a.out
1
ap1019@sharifvm:~$

Upvotes: 2

Views: 2483

Answers (5)

Bathsheba
Bathsheba

Reputation: 234685

Don't expect anything from this code. The behaviour of (float*)(&i); is undefined as the pointer types are unrelated.

float and int might not even be the same size. And you might be working on an architecture that stores float and int in entirely separate locations in memory. It's even possible that sizeof(float*) is not the same as sizeof(int*). Unlikely, but possible.

Upvotes: 1

Anton Savin
Anton Savin

Reputation: 41301

What you did is reinterpret_cast a pointer to int to pointer to float and retrieved a float value through the converted pointer.

In general, it's undefined behavior, but it so happened on your machine that int and float have the same size, and the bytes which represent int value 0x3f800000, also represent float value 1.

Upvotes: 5

Steve Jessop
Steve Jessop

Reputation: 279245

The bit-pattern that means 1065353216 as an integer (3f800000 in hex) happens in your implementation to mean 1 as a float. It's not guaranteed that this will be the case in all C++ implementations, although it is common since that's the bit-pattern representing 1 as a 32-bit IEEE 754 float.

Be aware also that your code violates strict aliasing, and therefore has undefined behaviour regardless of the bit patterns.

Upvotes: 1

Federico
Federico

Reputation: 1090

So I expect to see the 0x3f800000 in output, but It prints 1 instead. Why?

Because 0x3f800000 has the bit pattern 00111111100000000000000000000000 that if read according to the IEEE 754 standard is representing the float 1.0 enter image description here

Upvotes: 2

user872744
user872744

Reputation:

The conversion from int to float is wrong. You must do it like this:

unsigned int i=0x3f800000;
float f=(float)i;
cout<<f;

Upvotes: 1

Related Questions