在我的头文件中我定义了...
struct MD5_packet {
union{
unsigned long int longInt;
struct {
unsigned char byte0;
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
}bytesA;
}unionA;
... % 4 similar unions are also defined here with just the names differing
}
然后在 main 中我声明了...
struct MD5_packet *MD5_data;
unsigned char __attribute__ ((aligned (64))) state[88];
经过某个过程后,我有兴趣将 state
的前 16 个字节映射到一些 unsigned long int
或 unsigned int
属于 MD5_data
结构一部分的 union 。上面的代码显示了 MD5_packet
的结构体定义,其中成员为 longInt
,我希望简单地将 state
的前 4 个字节映射到 >longInt
union 。这样我就可以使用 MD5_data->unionA.longInt 来访问变量并在需要的地方分配它。我试图避免必须使用具有 16 个字符的结构和大量位操作来分配给我稍后将使用的变量。
所以在实现中...
MD5_data = (unsigned long int) &state[0];
unsigned long int anotherLongInt;
anotherLongInt = MD5_data->unionA.longInt;
结果如下。正如您所看到的,各个字节都已正确映射,但它们的顺序与我所期望的由 longInt
表示的顺序相反。 anotherLongInt
的值被写入,但也是以相反的顺序。
旁注:
即使我已经转换了 &state[0]
赋值,我还是收到了编译器警告。显然这不是最好的方法,因此任何指导都会有所帮助。
Assignment makes pointer form integer without a cast
最佳答案
int
或 long
中的字节顺序取决于平台(在互联网上搜索“little endian”或“big endian”)。
编辑:
对于常见的小/大端平台,您可以将您的structA
声明为
#include <endian.h>
...
struct {
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned char byte3;
unsigned char byte2;
...
#else
unsigned char byte0;
unsigned char byte1;
...
#endif
} bytesA;
关于c - 将数组映射到结构时的顺序相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229346/