Skip to content

Instantly share code, notes, and snippets.

@Inndy
Created March 13, 2014 04:08
Show Gist options
  • Save Inndy/9521754 to your computer and use it in GitHub Desktop.
Save Inndy/9521754 to your computer and use it in GitHub Desktop.
Peek raw data from structure/type in C++.
#include <cstdio>
template<typename T>
struct _bits_peeker {
union {
unsigned char bytes[sizeof(T)];
T value;
};
};
#define bits_peeker struct _bits_peeker
#define dump(D) { \
puts("In Hex:"); \
for (int i = 0; i < sizeof(D.value); i++) { \
printf("%.2X ", D.bytes[i]); \
} \
puts(""); \
puts("In Bits:"); \
for (int i = 0; i < sizeof(D.value); i++) { \
for (int j = 8; j >= 0; j--) { \
printf("%d", (D.bytes[i] & (1 << j)) >> j); \
} \
printf(" "); \
} \
}
int main () {
bits_peeker<double> peeker;
peeker.value = 123.456789;
printf("Value = %lf\n\n", peeker.value);
dump(peeker);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment