Original Post
I''m curious if using bit fields or using unions would be more efficient for the following program. I''m writing a class for a chess piece, and I''d like to keep the internal representation as small as possible (well, at least 32-bits or less). Originally I was using two ints, and doing &''s and >>''s to extract the data, but then it seemed more reasonable to use bit fields or unions.
Now, if I use bit fields, then the compiler will probably still use some &''s and >>''s, but it will be able to create the most efficient code for doing that.
The union on the other hand shouldn''t require any &''s and >>''s, but it should require a single array lookup (computing offset).
I''ll provide a little example of what I''m talking about.
In the class, you would access the data by doing simple _index = whatever;, and so on, but in the union, you would have to do something like _values[INDEX] = whatever;. I also will need to be able to quickly copy over a piece''s data, which would mean the union would be a nice choice, and then I could just copy the Piece''s _data field over if I needed to, and comparing pieces woud be simple too.
So which will work more efficiently? Or are they all equally fast?
Thanks,
Russell
class Piece {
public:
// methods here...
private:
unsigned : 6 _index;
unsigned : 1 _color;
unsigned : 4 _type;
unsigned : 1 _alive;
};
// Or, here''s the union example...
union Piece {
public:
// methods here...
private:
unsigned int _data;
unsigned char _values[4];
};