以下代码源自《深入理解计算机系统》
//
// int_tyoe_test.cpp
// Test
//
// Created by Cheng Sun on 12/15/16.
// Copyright © 2016 Cheng Sun. All rights reserved.
//
#include <stdio.h>
typedef unsigned char* byte_pointer; // 定义一个名为byte_pointer的指针,指向一个字节序列
void show_bytes(byte_pointer start, size_t len)
{
size_t i;
for(i = 0; i < len; ++i)
{
printf("%.2x ",start[i]); //"%.2x" 表示整数必须用至少两个数字的十六进制格式输出。
}
printf("\n");
}
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_pointer(void *x)
{
show_bytes((byte_pointer)&x, sizeof(void*));
}
void test_show_bytes(int val)
{
int ival = val;
float fval = (float) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
}
int main()
{
test_show_bytes(0x123456ff);
return 0;
}
代码运行结果:
ff 56 34 12
b8 a2 91 4d
28 f7 bf 5f ff 7f 00 00
Program ended with exit code: 0
最低有效字节在前面(在低地址),所以是小端法。
代码运行平台:Mac OS X,Xcode,64 bits。