-1

So I'm just diving into C during my first few days of classes. My professor proposed a question/ more of a challenge for us so I thought I'd propose it here.

float x,y,z;
x = 0.0;
y = 1.0;
z = -2.5;

He wanted us to display these numbers in binary and hexadecimal without using %x etc. He also hinted to use a union:

union U {
float y;
unsigned z;
};

Thank you for your time in advance. I'm just looking for help/ an explanation on how to develop such conversion.

zessed
  • 3
  • 4

1 Answers1

1

The correct way, not violating the strict aliasing rule would be to alias the float with a char array, which is allowed by the C standard.

union U {
  float y;
  char c[sizeof (float)];
};

This way you will be able to access the individual float y; bytes using the c array, and convert them into binary/hex using the very simple algorithm that can be easily found around (I will leave it up to you, as it is your assignment).

unwind
  • 391,730
  • 64
  • 469
  • 606
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • `unsigned char` has portability advantages over `char` as, rarely, `char` may have trap values. Further, a `char` that is _signed_ , slightly complicates conversion to hex/binary display. – chux - Reinstate Monica Sep 08 '16 at 16:05
  • @chux I was considering writing `unsigned` as it has advantages with converting based as well. But decided to leave it out to reduce the noise.. – Eugene Sh. Sep 08 '16 at 16:14