2010-03-18 72 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