Skip to content

Instantly share code, notes, and snippets.

@mpenick
Created August 15, 2014 17:50
Show Gist options
  • Save mpenick/bb24e7ce2075020938c2 to your computer and use it in GitHub Desktop.
Save mpenick/bb24e7ce2075020938c2 to your computer and use it in GitHub Desktop.
template<typename From, typename To>
inline To copy_cast(const From& from)
{
To to;
memcpy(&to, &from, sizeof(from));
return to;
}
int main() {
float f = 0.1;
int i = copy_cast<float, int>(f);
printf("0x%x\n", i); // Outputs: 0x3dcccccd
// Generated assembly
// GCC 4.1.2 (-O2 and -O3)
// movl $0x3dcccccd, 20(%rsp)
// movl 20(%rsp), %esi
// call printf
// Clang 3.4
// movl $1036831949, %esi ## imm = 0x3DCCCCCD
// xorl %eax, %eax
// callq _printf
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment