铸造结构转换成int [英] Casting struct into int

查看:140
本文介绍了铸造结构转换成int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有铸造结构到uint64_t中或任何其他int的清洁方式,因为结构上述< =的sizeof的诠释?
我能想到的唯一的事情只是一个OK的解决方案 - 使用工会。不过,我从来没有喜欢他们。

Is there a clean way of casting a struct into an uint64_t or any other int, given that struct in <= to the sizeof int? The only thing I can think of is only an 'ok' solution - to use unions. However I have never been fond of them.

让我补充一个code段澄​​清:

Let me add a code snippet to clarify:

typedef struct {
uint8_t field: 5;
uint8_t field2: 4;
/* and so on... */
}some_struct_t;

some_struct_t some_struct;
//init struct here

uint32_t register;

现在我怎么投some_struct捕捉其位寄存器uint32_t的订单。

Now how do i cast some_struct to capture its bits order in uint32_t register.

希望这使得它更清楚一点。

Hope that makes it a bit clearer.

推荐答案

我刚刚打了同样的问题,我有这样的联合解决它:

I've just hit the same problem, and I solved it with a union like this:

typedef union {
    struct {
        uint8_t field: 5;
        uint8_t field2: 4;
        /* and so on... */
    } fields;
    uint32_t bits;
} some_struct_t;

/* cast from uint32_t x */
some_struct_t mystruct = { .bits = x };

/* cast to uint32_t */
uint32_t x = mystruct.bits;

HTH,
亚历克斯

HTH, Alex

这篇关于铸造结构转换成int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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