Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 探索结构包装_C_Memory_Struct_Bits_Bit Fields - Fatal编程技术网

C 探索结构包装

C 探索结构包装,c,memory,struct,bits,bit-fields,C,Memory,Struct,Bits,Bit Fields,我想了解在压缩变量的情况下,结构是如何存储在一个小的endian机器上的 让我们假设我有以下带位字段的结构: struct my_struct { short a; short b: 6; short c: 10; int d; int e: 28; int f: 4; } 有人能解释一下这个结构是如何在内存中布局的吗。将每个成员设置为1并探索结构的位表示: #include <stdio.h> #include <limit

我想了解在压缩变量的情况下,结构是如何存储在一个小的endian机器上的

让我们假设我有以下带位字段的结构:

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

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

将每个成员设置为
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;
}
#包括
#包括
结构我的结构{
短a;
短b:6;
短c:10;
int d;
内特:28;
INTF:4;
};
内部主(空){
结构我的结构我的结构;
我的结构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(我的结构);
对于(int i=0;i=0;--i){
printf((字节>>i)&0x1?“1”:“0”);
}
printf(“”);
}
getchar();
返回0;
}

位字段的精确表示由实现定义。一些编译器从最低有效位开始打包,其他编译器从最高有效位开始打包;可能还有一些人还在做别的事情。同一个程序在使用不同的编译器编译时可能表现得非常不同。@FrançoisAndrieux我第一次和最后一次都有这个问题。我想知道上面的结构是如何在记忆中展现出来的。这对你自己探索这一点将是一个富有成效的练习。在将来,您将不得不多次执行此类操作,因此现在就开始吧。我建议您首先在每个
struct
成员中放置
1
值,然后探索转储。没有发布足够的代码来简化我们的工作。
0xIJ
这是什么?谢谢你的回答,这与我的计划和发现相符