深入理解计算机原理第二章家庭作业2.5.5~2.6.1

66 篇文章 0 订阅
51 篇文章 0 订阅

*2.55在你能够访问的不同机器上,使用show_bytes (文件show-bytes.c)编译并运行示例代码。 确定这些机器使用的字节顺序。

#include <stdio.h>

#include <string.h>

typedef unsigned char * byte_pointer;

void show_byte(byte_pointer x, int len);

void show_byte(byte_pointer x, int len) {

    for(int i = 0; i < len; i++)

        printf("%.2x ", x[i]);

    //%.2x保留至少两位有效数,x表示十六进制

    printf("\n");
}

运行结果:

  1023

机器使用的字节顺序为:低位在低地址,故为小端


*2.56 试着用不同的示例值来运行show_bytes的代码。

exp1:

1

exp2:

23.0

exp3:

”hello”


2.57 编写程序 show_short, show_long, show_double,它们分别打印类型为 short int 、long int 、和double的C语言对象的字节表示。请试着在几种机器上运行。

void show_short(pointer x){
    show_byte((byte_pointer)x,sizeof(short));
}

void show_long(pointer x){
    show_byte((byte_pointer)x,sizeof(long));
}

void show_double(pointer x){
    show_byte((byte_pointer)x,sizeof(double));
}

exp:

short num1=23;
long num2 =23432;
double num3=23.0;


**2.58编写过程is_little_endian,当在小端法机器上编译和运行时返回1,在大端法机器上编译运行 时则返回0。这个程序应该可以运行在任何机器上,无论机器的字长是多少。

int is_little_endian(){
    uint16_t num=0X0001;
    uint8_t *num2=(uint8_t*)&num;
    if(num2[0]==1)return 1;
    else return 0;
}

**2.59编写一个C表达式,使它生成一个字,由x的最低有效字节和y中剩下的字节组成。对于运算数x=0x89ABCDEF和y=0x76543210,就得到 0x765432EF。

答:

unsigned replace (unsigned x, unsigned y){
    return((x&0xff)|(y&~0xff))
}

答:

unsigned put_byte(unsigned x, unsigned char b, int i){
    unsigned res=0xff<<i*8;
    res=(x&~res)|b<<i*8;
    return res;
}

unsigned put_byte(unsigned x, unsigned char b, int i){
    unsigned res=0xff<<(i<<3);
    res=(x&~res)|b<<(i<<3);
    return res;
}

答:

int judge(int x){
    int num=(sizeof(x)-1)<<3;
    return !(~x)||!(~(x-1))||!(x<<8)||!(~(x>>num))||!(x<<num);
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值