Code to print the byte representation of program objects

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值