• Advertisement

Archived

This topic is now archived and is closed to further replies.

Bitfields in C

This topic is 5867 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, I''m making myself a nice Frac clone (Frac is like tetris only with a 3-dimensional board) in C. I know optimizations aren''t at all necessary, but I have the urge anyway, its just for fun. As it stands right now, I have a three dimensional array of unsigned chars [8][8][14] that tell me whether a piece occupies the board or not. Since the size of the board is so conveniently made 8x8, I was thinking I could made each line one byte, using a bitfield... struct { unsigned char b1 : 1 unsigned char b2 : 1 unsigned char b3 : 1 unsigned char b4 : 1 unsigned char b5 : 1 unsigned char b6 : 1 unsigned char b7 : 1 unsigned char b8 : 1 } line_s; I know that this would save on memory, but I heard some people mentioning that bitfields are slow... is there any truth to this?

Share this post


Link to post
Share on other sites
Advertisement
No. Declaring bitfields the way you did simply lets the compiler manage the masking rather than having you do it. It boils down to the same thing as manually setting up the mask and AND-ing/XOR-ing/OR-ing yourself.

Let the compiler work for you.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites

Just FYI...a bit field of type ''unsigned char'' is not part of the ISO standard. Make sure to check out your compiler''s documentation should you port this over to a different architecture/compiler.

Good luck with your game!

Share this post


Link to post
Share on other sites
true, in the standard...only int bitfields are supported, but i looked up the MSVC++ docs, and it supports bitfields for unsigned char =].

Share this post


Link to post
Share on other sites
Anytime I have used bitfields, I have always used the type "unsigned" by itself, for example:

  
struct whatever {
unsigned b1 : 4;
unsigned b2 : 4;
};


Russell

Share this post


Link to post
Share on other sites

  • Advertisement