对给定值进行操作

题目:
Write a C expression that will yield a word consisting of the least significant
byte of x, and the remaining bytes of y. For operands x = 0x89ABCDEF and y =
0x76543210, this would give 0x765432EF.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef unsigned char *byte_pointer;

void show_x_y() {
    int x = 0x89ABCDEF;
    int y = 0x76543210;
    byte_pointer start;

    for (int i = sizeof(int)-1; i > 0; i--) {
        start = (byte_pointer)&y;
        printf("%x", start[i]);
    }
    start = (byte_pointer)&x;
    printf("%x ",start[0]);
    printf(" x=%x,y=%x", x, y);
}

int main()
{
    show_x_y();

    return 0;
}

结果:
这里写图片描述

分析:

题目要求显示 x 的最后两位和 y 的前6位。

x=0x89abcdef,定义时就指明了十六进制,因此在内存中存储时,直接是每一位对应四位二进制,即 x=1000 1001 1010 1011 1100 1101 1110 1111(地址由低到高)。同理 y=0x76543210,在内存中存储为 y=0111 0110 0101 0100 0011 0010 0001 0000(地址由高到低)。因此在用指针从内存中读取数值时,每移动一次指针,实际上跨越了二进制的八位,也就是十六进制的两位,所以,用start[0]读取 x 时,结果为 ef,而不是 f 。同理,读取 y 时,因为题目要求不读最后两位,所以,指针应该从 start[1] 开始,又由于题目要求显示格式为从左到右从高位到低位,因此我们应该倒着读取,即从 start[sizeof(int)-1] 读到 start[1] 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值