Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c - Converting Bit Field to int

I have bit field declared this way:

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

I also have int array, and I want to get int value from this array, that represents the actual value of this bit field (which is actually some kind of machine word that I have the parts of it, and I want the int representation of the whole word).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...