【问题标题】:Explore structure packaging探索结构包装
【发布时间】:2017-10-05 19:11:29
【问题描述】:

我想了解结构如何存储在小端机器上以及打包变量的情况下。

假设我有以下带有位域的结构:

struct my_struct {
    short a;
    short b: 6;
    short c: 10;
    int d;
    int e: 28;
    int f: 4;
} 

谁能解释一下这个结构是如何在内存中布局的。

【问题讨论】:

  • 位字段的精确表示是实现定义的。一些编译器从最低有效位开始打包它们,而另一些则从最高有效位开始打包。可能还存在那些做其他事情的人。当使用不同的编译器编译时,相同的程序可能会有不同的表现。
  • @FrançoisAndrieux 我第一次也是最后一次有这个问题。我想知道上面的结构在内存中是如何布局的
  • 您自己探索这将是一个富有成效的练习。未来你将不得不做很多很多次这样的事情,所以现在就开始吧。
  • 我建议您首先在每个 struct 成员中放置一个 1 值并探索转储。发布的代码不足以让我们轻松使用。
  • 0xIJ 那是什么?

标签: c memory struct bits bit-fields


【解决方案1】:

将每个成员设置为1并探索结构的位表示:

#include <stdio.h>
#include <limits.h>

struct my_struct {
    short a;
    short b : 6;
    short c : 10;
    int d;
    int e : 28;
    int f : 4;
};

int main(void) {
    struct my_struct my_struct;

    my_struct.a = 0x1;
    my_struct.b = 0x1;
    my_struct.c = 0x1;
    my_struct.d = 0x1;
    my_struct.e = 0x1;
    my_struct.f = 0x1;

    int size = sizeof(my_struct);

    for (int i = 0; i < size; ++i) {
        unsigned char byte = *((unsigned char *)&my_struct + i);
        for (int i = CHAR_BIT - 1; i >= 0; --i) {
            printf((byte >> i) & 0x1 ? "1" : "0");
        }
        printf(" ");
    }

    getchar();
    return 0;
}

【讨论】:

  • 感谢您的回答,这与我的程序和发现相符
猜你喜欢
  • 2019-05-10
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多