Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting struct into int

Tags:

c

casting

struct

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.

like image 893
GoTTimw Avatar asked Aug 10 '12 14:08

GoTTimw


3 Answers

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

like image 52
Alex Zeffertt Avatar answered Oct 20 '22 16:10

Alex Zeffertt


A non-portable solution:

struct smallst {
  int a;
  char b;
};

void make_uint64_t(struct smallst *ps, uint64_t *pi) {
  memcpy(pi, ps, sizeof(struct smallst));
}

You may face problems if you, for example, pack the struct on a little-endian machine and unpack it on a big-endian machine.

like image 22
perreal Avatar answered Oct 20 '22 17:10

perreal


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

like image 40
omry155 Avatar answered Oct 20 '22 17:10

omry155