Wednesday, March 14, 2007

Typecasting without type conversion

All the C-buffs out there probably already know about this but in order to just cast a type to another one without the implicit type conversion, some pointer games need to be played. E.g. if you want to cast a float into a type that's more suited for bitwise operations, say an unsigned integer, you don't want the whole type conversion thing to round off the float and set the integer to, well, the integer representation of that float. Instead, you want to perform a bitwise exact copy, something that

float f;
unsigned i = (unsigned) f;
i = unsigned(f);
i = const_cast<unsigned>(f);

all fail to do. Instead, use

unsigned i = *(unsigned *) &f;

Easy as that, with no need for memcpy:s or other unsafe operations. To get the correct result though, make sure that whatever datatypes are involved are of the same size, e.g. float and ints on any 32-bit system.

No comments:

Post a Comment