Casting struct into int

Viewed 25914

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.

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;

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

Hope that makes it a bit clearer.

4 Answers

you can use pointers and it will be easy for example:

struct s {
    int a:8;
    int b:4;
    int c:4;
    int d:8;
    int e:8; }* st;

st->b = 0x8;
st->c = 1;
int *struct_as_int = st;

hope it helps

You can cast object's pointer to desired type and then resolve it. I assume it can be a little bit slower than using unions or something else. But this does not require additional actions and can be used in place.

Short answer:

*(uint16_t *)&my_struct

Example:

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

typedef struct {
    uint8_t field1;
    uint8_t field2;
} MyStruct;

int main() {
    MyStruct my_struct = {0xFA, 0x7D};
    uint16_t num_my_struct = *(uint16_t *)&my_struct;
    printf("%X \n", num_my_struct);  // 7DFA

    return 0;
}
Related