从 struct bitfield 以十六进制打印完整 uint32_t

Print full uint32_t in hex from struct bitfield

我的结构如下:

struct myCoolStuff{
    uint32_t stuff1 :  4;
    uint32_t stuff2 :  4;
    uint32_t stuff3 : 24;
    uint32_t differentField;
}

如何将这些字段组合成十六进制格式以便打印到屏幕或写入文件?谢谢你。

struct myCoolStuff data = {.stuff1=0xFF, .stuff2=0x66, .stuff3=0x112233, .differentField=99};

printf("my combined stuff is: %x\n", <combined stuff>);
printf("My full field is: %x\n", data.differentField);

Expected Output: 
my combined stuff is: 0xFF66112233 
My different field is: 99

在此结构中添加一个联合,您可以使用它来重新解释字段。

struct myCoolStuff{
    union {
        struct {
            uint32_t stuff1 :  4;
            uint32_t stuff2 :  4;
            uint32_t stuff3 : 24;
        };
        uint32_t stuff;
    }
    uint32_t fullField;
};

...

printf("my combined stuff is: %x\n", data.stuff);

也许这样的事情会有所帮助:

unsigned char *ptr = (unsigned char *)&data; // store start address
int size = sizeof(myCoolStuff); // get size of struct in bytes
while(size--) // for each byte
{
    unsigned char c = *ptr++; // get byte value
    printf(" %x ", (unsigned)c); // print byte value
}

首先,将0xFF放入4位变量后,你无法从0xFF中取出0xFF0xFF 占用 8 位。 0x66.

相同

至于将位域重新解释为单个整数,您可以, 以非常不可移植的方式(存在big-endian/little-endian问题和填充位的可能性)使用union.

( 这个:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

struct myCoolStuff{
    union{
        struct {
        uint32_t stuff1 :  4;
        uint32_t stuff2 :  4;
        uint32_t stuff3 : 24;
        };
        uint32_t fullField;
    };
};
struct myCoolStuff data = {.stuff1=0xFF, .stuff2=0x66, .stuff3=0x112233};

int main()
{
    printf("My full field is: %" PRIX32 "\n", data.fullField);
}

在我的 x86_64 上打印 1122336F。 )

要做到这一点 便携 你可以简单地获取位域并手动将它们放在一起:

这个:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

struct myCoolStuff{
        uint32_t stuff1 :  4;
        uint32_t stuff2 :  4;
        uint32_t stuff3 : 24;
};
struct myCoolStuff data = {.stuff1=0xFF, .stuff2=0x66, .stuff3=0x112233};

int main()
{
    uint32_t fullfield = data.stuff1 << 28 | data.stuff2 << 24 | data.stuff3;
    printf("My full field is: %" PRIX32 "\n", fullfield);
}

应该在它编译的任何地方打印 F6112233(不保证 uint32_t 存在(尽管在 POSIX 平台上它会存在);uint_least32_t 本来是更便携。)

注意确保 data.stuff1 有足够的位可以移动 28。你的是因为它是输入 uint32_t,但是这样做会更安全,例如,使用 (data.stuff1 + 0UL)<<28(data.stuff1 + UINT32_C(0))<<28 并且第二个班次也是如此。

乘法(至少使用 uint32_t 数学),然后使用匹配的说明符打印。

#include <inttypes.h>

struct myCoolStuff{
    uint32_t stuff1 :  4;
    uint32_t stuff2 :  4;
    uint32_t stuff3 : 24;
    uint32_t differentField;
}

uint32_t combined stuff = ((uint32_t) data.stuff1 << (4 + 24)) | 
    ((uint32_t) data.stuff2 <<  24) |  data.stuff3;

printf("my combined stuff is: 0x%" PRIX32 "\n", combined stuff);
printf("My full field is: %x\n", data.differentField);