Casting struct into int

前端 未结 3 434
长情又很酷
长情又很酷 2021-01-04 19:29

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\' sol

3条回答
  •  时光取名叫无心
    2021-01-04 19:58

    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, Alex

提交回复
热议问题