This code uses casting to circumvent the type system. Firstly, cast pointers to byte_pointer, pointing to an object of type "unsigned char" which represents a single byte. Seondly, printf and cout are used to print the byte representation, and static_cast is needed when using cout.
// Code to print the byte representation of program objects
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <Windows.h>
using namespace std;
typedef unsigned char* byte_pointer;
void show_bytes(byte_pointer start, int len)
{
for (int i=0; i!=len; ++i)
cout << " " << hex << setw(2) << setfill('0')
<< static_cast<int>(start[i]);
//printf(" %.2x", start[i]);
cout << endl;
}
void show_int(int x)
{
show_bytes((byte_pointer) &x, sizeof(int));
}
void show_float(float x)
{
show_bytes((byte_pointer) &x, sizeof(float));
}
void show_double(double x)
{
show_bytes((byte_pointer) &x, sizeof(double));
}
void show_pointer(void* x)
{
show_bytes((byte_pointer) &x, sizeof(void*));
}
int _tmain(int argc, _TCHAR* argv[])
{
int i = 1000;
show_int(i);
float f = 1;
show_float(f);
double d = 1;
show_double(d);
show_pointer(&d);
Sleep(5000);
return 0;
}
Running results on Win32 and x64 are represented on the two figures below.
Figure 1 Running results on Win32 Figure 2 Running results on x64
From the two figures, it's concluded that the microprocessor of the machine follows the convention of little endian. What's more, a pointer(e.g. a variable declared as being of type "double *") uses the full word size of the machine.