2010-03-18 70 views
12

我有位域聲明是這樣的:轉換位字段爲int

typedef struct morder { 
    unsigned int targetRegister : 3; 
    unsigned int targetMethodOfAddressing : 3; 
    unsigned int originRegister : 3; 
    unsigned int originMethodOfAddressing : 3; 
    unsigned int oCode : 4; 
} bitset; 

我也有int數組,我想從這個數組,表示此位字段的實際價值得到int值(這實際上是某種機器詞,我有它的部分,我想整個詞的整數表示)。

非常感謝。

+3

@shaharg:我認爲你對你的語言不太確切。位字段是結構中的單個字段,但您似乎將整個結構稱爲「位字段」。 – JXG 2010-03-18 10:12:06

回答

13

您可以使用一個聯盟:

typedef union bitsetConvertor { 
    bitset bs; 
    uint16_t i; 
} bitsetConvertor; 

bitsetConvertor convertor; 
convertor.i = myInt; 
bitset bs = convertor.bs; 

或者你可以使用一個投:

bitset bs = *(bitset *)&myInt; 

或者你可以在聯盟內使用匿名結構:

typedef union morder { 
    struct { 
     unsigned int targetRegister : 3; 
     unsigned int targetMethodOfAddressing : 3; 
     unsigned int originRegister : 3; 
     unsigned int originMethodOfAddressing : 3; 
     unsigned int oCode : 4; 
    }; 

    uint16_t intRepresentation; 
} bitset; 

bitset bs; 
bs.intRepresentation = myInt; 
+0

這個匿名工會如何完成任何事情? – zubergu 2013-09-10 19:25:56

+0

@zubergu,方便。當然不是絕對需要的。 – strager 2013-09-11 21:41:06

+0

Downvoted:'bitset bs = *(bitset *)&myInt;'是打破*嚴格別名規則*的典型例子。 – user694733 2017-06-28 11:52:58

3

當然 - 只是使用聯合。然後,您可以以16位整數或個別位域的方式訪問您的數據,例如

#include <stdio.h> 
#include <stdint.h> 

typedef struct { 
    unsigned int targetRegister : 3; 
    unsigned int targetMethodOfAddressing : 3; 
    unsigned int originRegister : 3; 
    unsigned int originMethodOfAddressing : 3; 
    unsigned int oCode : 4; 
} bitset; 

typedef union { 
    bitset b; 
    uint16_t i; 
} u_bitset; 

int main(void) 
{ 
    u_bitset u = {{0}}; 

    u.b.originRegister = 1; 
    printf("u.i = %#x\n", u.i); 

    return 0; 
} 
16

請做不是使用聯合。或者,相反,通過使用聯合來了解你在做什麼 - 最好在使用聯合之前。

正如你在this answer中看到的那樣,不要依賴位域是可移植的。特別是對於你的情況,一個結構內的位域的排序是依賴於實現的。

現在,如果你的問題是,你怎麼能打印出位域結構作爲一個int,偶爾的私人審查,當然,工會是偉大的。但你似乎想要你的位域的「實際價值」。所以:如果你只在這一臺機器/編譯器組合上工作,並且你不需要依賴就可以得到int的數學值,只要有意義,你可以使用聯合。但是,如果您可能會移植您的代碼,或者您需要int的「實際值」,則需要編寫位操作代碼以將位字段置入正確的int位。

+6

+1'結構內位域的排序是依賴於實現的' – Lazer 2010-03-19 18:10:23

+0

實現是否依賴於依賴於平臺的編譯器,依賴於平臺還是兩者? – gsingh2011 2013-01-18 02:53:12

+0

@ gsingh2011,兩者。特定架構的特定編譯器可以完成它認爲最好的任務。 – JXG 2013-01-23 08:51:48