从结构位域以十六进制打印完整的uint32_t

时间:2018-11-20 15:38:18

标签: c io bit-fields

我的结构如下:

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

4 个答案:

答案 0 :(得分:3)

首先,将0xFF放入4位变量后,您将无法获得0xFF0xFF占8位。与0x66相同。

关于将位域重新解释为单个整数,您可以, 以非常不便携的方式(存在大尾数/小尾数问题以及填充位的可能性)使用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且第二个班次相同。

答案 1 :(得分:1)

在此结构内添加一个联合,可用于重新解释字段。

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

答案 2 :(得分:1)

相乘(至少使用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);

答案 3 :(得分:0)

也许这样会有所帮助:

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
}