c - 探索结构包装

标签 c memory struct bit bit-fields

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

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

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;
}

关于c - 探索结构包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593147/

相关文章:

c - 如何使用 rand 函数使数字在特定范围内?

c - 函数中的 Malloc 结构数组

c - 同一 C 程序的不同输出

json - 当另一个包访问时,Json 解码后结构为空

c - 按位逻辑检查?

java - 无法创建新的 native 线程错误 - 但使用的线程很少

C++ 按值返回 - 里面的指针会发生什么?

c - Lua:垃圾回收+用户数据

c++ - 尝试使用指向结构 vector 的指针访问结构类型时出错

C程序不等待用户输入值