2013-11-26 14 views
0

在我定義我的頭文件...相反的順序時,映射數組結構

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個字節映射到作爲MD5_data結構的一部分的幾個unsigned long intunsigned int聯合。上面的代碼顯示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]分配的編譯器警告。顯然這不是最好的方式,所以任何指導都會有所幫助。在intlong

Assignment makes pointer form integer without a cast 

回答

0

字節順序取決於平臺(搜索「小端」或在互聯網上「大端」)。

編輯:

常見小/大端平臺,您可以聲明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; 
+0

有沒有辦法強制執行一定的字節序只是這個映射,這樣的順序是正確的? – Falimond

+0

那麼這個#ifdef塊會進入struct> union> struct定義中?我不明白爲什麼要顛倒名稱byte3 ... byte2 ... byte1 ...或byte0 ... byte1 ... byte2 ...的順序,因爲它們只是變量名稱。該名稱不會定義訂單。 – Falimond

+0

是的;我更新了示例 – ensc