将struct转换为int
对于非可移植解决方案中的结构,是否有一种干净的方法可以将该结构强制转换为uint64_t或任何其他int:将struct转换为int,c,casting,struct,C,Casting,Struct,对于非可移植解决方案中的结构,是否有一种干净的方法可以将该结构强制转换为uint64_t或任何其他int: struct smallst { int a; char b; }; void make_uint64_t(struct smallst *ps, uint64_t *pi) { memcpy(pi, ps, sizeof(struct smallst)); } 例如,如果您将结构打包到一台小端计算机上,然后在一台大端计算机上解包,您可能会遇到问题。我刚刚遇到了同样的问题,
struct smallst {
int a;
char b;
};
void make_uint64_t(struct smallst *ps, uint64_t *pi) {
memcpy(pi, ps, sizeof(struct smallst));
}
例如,如果您将结构打包到一台小端计算机上,然后在一台大端计算机上解包,您可能会遇到问题。我刚刚遇到了同样的问题,我用一个像这样的并集解决了它:
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;
嗯,,
Alex你可以使用指针,这将很容易 例如:
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;
希望这有帮助不“喜欢”工会?工会以一种清晰、可维护的方式完成您想要做的事情。什么是“OK”呢?我不知道如何回答这个问题,而不知道你到底需要这个做什么。请提供更多信息。有一种方法可以将结构指针强制转换为int指针,但很可能会导致未定义的行为。如果你更喜欢未定义的行为而不是工会,这就说明了如何进行黑客攻击。我也不喜欢工会——他们有太多的政治权力:):)为什么要停止使用memcpy呢?您可以使用某种宏编辑器来修改源代码,以使用memcpy()调用所有需要在任何符合要求的编译器中进行类型转换的赋值,并且在许多编译器上也需要使用
-fno严格别名
或类似选项。
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;