문제

비트 필드가 이런 식으로 선언했습니다.

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 값을 얻고 싶습니다.이 비트 필드의 실제 값을 나타냅니다 (실제로는 그 부분이있는 어떤 종류의 기계 단어입니다. int 표현을 원합니다. 전체 단어).

정말 감사합니다.

도움이 되었습니까?

해결책

You can use a union:

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

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

Or you can use a cast:

bitset bs = *(bitset *)&myInt;

Or you can use an anonymous struct within a union:

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;

다른 팁

Please, please, do not use a union. Or, rather, understand what you're doing by using a union--preferably before you use one.

As you can see in this answer, do not rely on bitfields to be portable. Specifically for your case, the ordering of the bitfields within a struct is implementation-dependent.

Now, if your question was, how can you print out the bitfield struct as an int, for occasional private review, sure, unions are great. But you seem to want the "actual value" of your bitfields.

So: if you only work on this one machine/compiler combination, and you don't need to rely on the mathematical value of the int, so long as it makes sense, you can use unions. But if you might port your code, or if you need the "actual value" of the int, you need to write bit-manipulation code to get the bit fields into the right int bits.

Sure - just use a union. You can then access your data either as a 16 bit int or as individual bit-fields, e.g.

#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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top