Casting struct into int

前端 未结 3 433
长情又很酷
长情又很酷 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 20:09

    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.

提交回复
热议问题