将数组映射到struct时的反转顺序

时间:2013-11-26 22:29:36

标签: c arrays struct mapping

在我的头文件中,我定义了......

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

  }

然后在主要方面我宣布......

struct MD5_packet *MD5_data;
unsigned char __attribute__ ((aligned (64))) state[88];

在某个过程之后,我感兴趣的是将state的前16个字节映射到unsigned long int个结构中的几个unsigned intMD5_data个联合体。上面的代码显示了MD5_packet与成员longInt的结构定义,我希望将state的前4个字节映射到longInt联合。这样我就可以使用MD5_data->unionA.longInt来访问变量并在需要的地方分配它。我试图避免使用带有16个字符和大量位操作的结构来分配我稍后将使用的变量。

所以在实施中......

MD5_data = (unsigned long int) &state[0];
unsigned long int anotherLongInt;
anotherLongInt = MD5_data->unionA.longInt;

结果如下。正如您所看到的那样,单个字节被正确映射,但是它们的顺序与我在longInt表示时的预期相反。写入anotherLongInt的值但也按相反的顺序写入。

Watch window results

旁注: 即使我投了它,我也会收到&state[0]赋值的编译器警告。显然这不是最好的方式,所以任何指导都会有所帮助。

Assignment makes pointer form integer without a cast

1 个答案:

答案 0 :(得分:0)

intlong中的字节顺序取决于平台(在互联网中搜索“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;