Manivel Sundaresan
Manivel Sundaresan

Reputation: 157

What's the output of the program?

I saw the following code in http://indiabix.com/ Can anyone explain the code?

#include<stdio.h>
#include<math.h>

int main()
{
   float a=5.375;
   char *p;
   int i;
   p = (char*)&a;

   for(i=0; i<=3; i++)
   {
         printf("%02x\n", (unsigned char)p[i]);
   }

   return 0;
}

And the result is

00 00 AC 40

.

Upvotes: 0

Views: 119

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

This program reinterprets the memory where a float is stored. Depending on the size of destination (float here), its representation (Assume IEEE754), and machine endianness it may give different outputs.

In this case, it appears machine is little endian and float representation is IEEE754.

You can use this online tool to visualize the float reprentation in binary.

+-------------+-----------------------------------------------------------+
| Input       | 5.375                                                     |
+-------------+-----------------------------------------------------------+
| Binary32    | 40 AC 00 00                                               |
+--------+----+-----+---------------+-------------------------------------+
| Status | Sign [1] | Exponent [8]  | Significand [23]                    |
+--------+----------+---------------+-------------------------------------+
| Normal |   0 (+)  | 10000001 (+2) | 1.01011000000000000000000 (1.34375) |
+--------+----------+---------------+-------------------------------------+

Loosely related topic: Strict aliasing rule.

Upvotes: 5

Related Questions