I have a unsigned char*. Typically this points to a chunk of data, but in some cases, the pointer IS the data, ie. casting a int value to the unsigned char* pointer (unsigned char* intData = (unsigned char*)myInteger;), and vice versa.
However, I need to do this with a float value, and it keeps giving me conversion errors.
unsigned char* data;
float myFloat = (float)data;
How can I do this?
If your compiler supports it (GCC does) then use a union. This is undefined behavior according to the C++ standard.
This works if
sizeof(unsigned char *) == sizeof(float). If pointers are larger than floats then you have to rethink your strategy.See wikipedia article on type punning and in particular the section on use of a union.
GCC allows type punning using a union as long as you use the union directly and not typecasting to a union… see this IBM discussion on type-pun problems for correct and incorrect ways of using GCC for type punning.
Also see wikipedia’s article on strong and weak typing and a well researched article on type punning and strict aliasing.