【问题标题】:What's this C code means? - Computer Systems A Programmer's Perspective这个C代码是什么意思? - 计算机系统程序员的观点
【发布时间】:2016-08-26 07:22:52
【问题描述】:

我想知道下面的函数show_int()实际上是做什么的……

此代码位于 Computer Systems A Programmer's Perspective 的第 28 页。

#include <stdio.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len) {
    int 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 main() {
    show_int(20);
    getchar();
}

【问题讨论】:

    标签: c


    【解决方案1】:

    最重要的是要了解*byte_pointer(又名unsigned char)的演员表:

    (byte_pointer) &x
    

    您可能会将其视为将指向 int(在您的情况下为 20)的指针转换为一系列字节(可以是 4 或 8 甚至更多字节,具体取决于架构)。

    show_bytes() 函数所做的只是迭代一个字节数组以显示其后续字节,并将其格式化为hexadecimal format

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多