csapp2 信息的表示和处理

介绍

深入理解计算机系统第二章的家庭作业

2.55

#include <stdio.h>

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(float x){
    show_bytes((byte_pointer) &x, sizeof(float));
}

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

My laptop is little endian.

2.56

int x = 12345;
float f = 12345.54321;
int *p = &x;
show_int(x);
show_float(f);
show_pointer(p);

39 30 00 00
2c e6 40 46
94 f5 af a0 5f 00 00 00

2.57

void show_short(short x){
    show_bytes((byte_pointer) &x, sizeof(short));
}

void show_long(long x){
    show_bytes((byte_pointer) &x, sizeof(long));
}

void show_double(double x){
    show_bytes((byte_pointer) &x, sizeof(double));
}

int main()
{
    short x = 23123;
    long y = 23123124123;
    double z = 12345.1234521;
    show_short(x);
    show_long(y);
    show_double(z);
    return 0;
}

53 5a
9b df 3e 62
10 46 47 cd 8f 1c c8 40

2.58

bool is_little_endian() {
    int i = 1;
    byte_pointer start = (byte_pointer)&i;
    return start[0] == 1;
}

2.59

int main()
{
    int x = 0x89abcdef;
    int y = 0x76543210;
    printf("%Xn", (y >> 8 << 8) + (x & 0xFF));
    printf("%Xn", (y & ~0xFF) + (x & 0xFF));
}

765431EF
765431EF

2.60

unsigned replace_byte(unsigned x, int i, unsigned char b) {
    unsigned right, result;
    int m = pow(16, i * 2);
    right = x % m;
    result = (((x >> 8 * (i + 1) << 8) + b) << 8 * i) + right;
    return result;
}

int main()
{
    unsigned x = 0x12345678;
    unsigned char b = 0xAB;
    printf("%Xn", replace_byte(x, 0, b));
    printf("%Xn", replace_byte(x, 1, b));
    printf("%Xn", replace_byte(x, 2, b));
    printf("%Xn", replace_byte(x, 3, b));
}