Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret a 4 byte int as a 4 byte float

Tags:

c++

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:~$
like image 247
Ebrahim Ghasemi Avatar asked Apr 09 '26 08:04

Ebrahim Ghasemi


2 Answers

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.

like image 120
Anton Savin Avatar answered Apr 10 '26 22:04

Anton Savin


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

like image 34
Federico Avatar answered Apr 10 '26 22:04

Federico



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!