位字段用C含结构的工会结构 [英] Bitfields in C with struct containing union of structs

查看:142
本文介绍了位字段用C含结构的工会结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

唔...那为什么,当我打印的sizeof(结构MYSTRUCT),它输出(而不是2)3本code <? / p>

Hm... why is it that, when I print sizeof(struct MyStruct), it outputs 3 (instead of 2) for this code?

#pragma pack(push, 1)
    struct MyStruct
    {
        unsigned char a : 6;
        union
        {
            struct
            {
                unsigned int b : 9;
            };
        };
    };
#pragma pack(pop)

在这重要的情况下,我在Windows 7上运行x64的GCC的MinGW 4.5.0,但说实话,结果是怪异够我说,我不认为编译器和OS太大的关系在这里。 :\\

In case it matters, I'm running MinGW GCC 4.5.0 on Windows 7 x64, but honestly, the result is weird enough for me that I don't think the compiler and the OS matter too much here. :\

推荐答案

您不能开始在未字节对齐地址领域。
你期待:

You can't have the field starting at an address that is not byte aligned. You're expecting:

6 bits + 9 bits -> 15 bits -> 2 bytes

但你得到的是:

6 bits -> 1 byte
9 bits -> 2 bytes
total ->  3 bytes

的数据被存储为:

The data is being stored as:

| 1 byte | 2 byte |3 byte | 
 aaaaaaXX bbbbbbbb bXXXXX  

当你期待:

| 1 byte | 2 byte |
 aaaaaabb bbbbbbbX  

编辑:
为了澄清基于以下意见:

edit: To clarify based on the comments below:

工会(和含结构)必须字节对齐。这不要紧,内容只有9位,工会/结构本身是一个完整的16位。请注意,你不能做到以下几点:

The union (and the containing struct) must be byte aligned. It doesn't matter that the contents are only 9 bits, the union/struct itself is a full 16 bits. Notice that you cannot do the following:

struct MyStruct
{
    unsigned char a : 6;
    union
    {
        struct
        {
            unsigned int b : 9;
        } c:9;
    } d:9;
};

以C不会让您指定的整个结构的比特大小。

As C won't let you specify the entire struct's bit-size.

这篇关于位字段用C含结构的工会结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆