对给定值进行操作

来源:互联网 发布:网络黄金王晨芳照片 编辑:程序博客网 时间:2024/06/02 17:40

题目:
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
原创粉丝点击