2016-05-12 58 views
2
#include<iostream> 
using namespace std; 
union swap_byte {    //This code is for union 
public: 
    void swap(); 
    void show_byte(); 
    void set_byte(unsigned short x); 
    unsigned char c[2]; 
    unsigned short s; 
}; 

void swap_byte::swap()   //swaping the declared char c[2] 
{ 
    unsigned char t; 
    t = c[1]; 
    c[1] = c[0]; 
    c[0] = t; 
} 
void swap_byte::show_byte() 
{ 
    cout << s << "\n"; 
} 
void swap_byte::set_byte(unsigned short x)  //input for the byte 
{ 
    s = x; 
} 
int main() 
{ 
    swap_byte b; 
    b.set_byte(49034); 
    b.show_byte(); 
    b.swap(); 
    b.show_byte(); 
    cin.get(); 
    return 0; 
} 

我無法理解工會的目的,並且我通過上面的代碼看到了工會的實施,但感到困惑,請解釋代碼的作用以及工會的工作方式。有人可以解釋工會在這行代碼中如何工作以及如何交換數字?

+0

它本質上是endian轉換短路。如果你檢查c [0]和s的地址,你會發現它們指向內存中的同一個地方。作者這樣做的意思是說:s =((s >> 8)&0x0F)| ((s << 8)&0xF0)。 – Aumnayan

回答

6

union的是一種特殊的,其中部件重疊的結構,所以swap_byte佈局是一樣的東西:

|  |  | char c[2] 
------------- 
|   | short s 

但是這發生在相同的2個存儲器字節。這就是爲什麼交換c的單個字節產生交換short號碼的最相關且最不相關的字節的效果。

請記住,這可能是脆弱的,它不是最好的方式來做到這一點,因爲你必須確保多個方面。另外,默認情況下,訪問不同於最後一個集合的union字段會在C++中產生未定義的行爲(雖然它允許在C中)。這是一個很少需要的舊技巧。

相關問題