Help: Typ conversion!!!!

Hello,

i would like to convert a float or double variable into unsigned char variable and back.

1
2
3
4
float number_float = 23.453f; 
unsigned char* number_char = (unsigned char*)malloc(sizeof(float));
number_char = reinterpret_cast<unsigned char*> (&number_float);
float* number_float_0 = reinterpret_cast<float*>(&number_char);


I am not getting the same value back.. why?

thank you
you print out the content of the wrong variable:
 
cout << number_float_0 << endl;

 
4.58984e-039
Let me remind you that:

A float's size is 32-bit
A char (unsigned too)'s size is 8-bit.

What you are doing is convert a POINTER TO float to a POINTER TO char.

Their size is equal, but you're doing it wrong.

1
2
3
4
5
float NumFloat = 2.f;
char * Pointer = (char *)(&NumFloat);
float * PointerFloat = (float *)(Pointer);
float DestFloat = *PointerFloat;
cout << DestFloat << endl;


This breaks C++'s type safety.
Be careful about that, don't play with it if you don't know pointers.

Your example featured a 4-byte memory leak and bad castings.
Last edited on
Topic archived. No new replies allowed.