Skip to content

Instantly share code, notes, and snippets.

@mpenick
Created August 15, 2014 19:24
Show Gist options
  • Save mpenick/4d952490585bf391233c to your computer and use it in GitHub Desktop.
Save mpenick/4d952490585bf391233c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
template<typename From, typename To>
inline To copy_cast(const From& from)
{
To to;
memcpy(&to, &from, sizeof(from));
return to;
}
float one() {
return floorf((float)rand() / RAND_MAX) + 1.0f; // Always returns 1.0f
}
int main() {
#ifdef COPY_CAST
float f = one();
register int* fbits = copy_cast<float*, int*>(&f);
f += one();
printf("original: %d alias: %d floating: %f\n", *copy_cast<float*, int*>(&f), *fbits, f);
#else
float f = one();
register int* fbits = (int*)(&f);
f += one();
printf("original: %d alias: %d floating: %f\n", *((int*)&f), *fbits, f);
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment