深入理解计算机系统 练习题2.5 答案与分析

测试代码

#include <stdio.h>  
#include "stdafx.h"
#include <iostream>
typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, size_t len) {
    size_t  i;
    for (i = 0; i < len;i++) {
        printf(" %.2x", start[i]);
    }
    printf("\n");
}

void show_int(int x) {
    show_bytes((byte_pointer)&x, sizeof(int));
}

void show_float(int x) {
    show_bytes((byte_pointer)&x, sizeof(float));
}

void show_pointer(int *x) {
    show_bytes((byte_pointer)&x, sizeof(void *));
}

int main() {
    int val = 0x87654321;
    byte_pointer valp = (byte_pointer) &val;
    show_bytes(valp, 1);
    show_bytes(valp, 2);
    show_bytes(valp, 3);
    system("pause");

}

运行结果
这里写图片描述
我是在WIN10下跑的程序,由此可见WINDOW是小端法,先明确此点。
根据0x87654321这个数值,因为是16进制,所以需要4个字表示一个数字,一个字节保存2个数字,在小端法中21为数组下标0,43为数组下标1,65为数组下标2,87为数组下标3,正好是32位int类型。根据代码所以结果为

列名 小端法 大端法
show_bytes(valp, 1); 21 87
show_bytes(valp, 2); 21 43 87 65
show_bytes(valp, 3); 21 43 56 87 65 43

猜你喜欢

转载自blog.csdn.net/ciqingloveless/article/details/82684036