开发者

Most effective way to store more booleans

I need to store exactly four booleans in my struct in c. Yes I could use four integers or put them into an array but I would like to do it a bit nicer. I was thinking about an int like "0000" where each number would represen开发者_JS百科t the boolean value, but then when editing I cant edit only the one digit, right? That doesnt look perfect either...

Thanks for any ideas


You could use a bitfield struct:

struct foo {
  unsigned boolean1 : 1;
  unsigned boolean2 : 1;
  unsigned boolean3 : 1;
  unsigned boolean4 : 1;
};

You can then easily edit each boolean value separately, for example:

struct foo example;
example.boolean1 = 1;
example.boolean2 = 0;


Using an int like "0000" is called using a bit field and is done quite regularly in practice. Yes, you can edit single values using bit shifting. Personally, I'd rather use an int to a bitfield struct as you can expand up to 32 values (if you're using a 32 bit int of course) without having to modify the struct.


If you're storing millions of these, do it as packed bits.

If you need to access it millions of times per second, do it as ints (or shorts or chars).

If neither, then it doesn't matter.

If both, then you may have some serious performance tuning to do.


Could be done using

http://en.wikipedia.org/wiki/Stdbool.h

bool a = true;  // Could also be 'bool a = 1;'


struct _eMyBool
{
    int m_iOne : 1;
    int m_iTwo : 1;
    int m_iThree : 1;
    int m_iFour : 1;
} eMyBool;

However dont even think it is the most efficient way to use boolean.

Because the additionnal assembly code generated so as to handle this has a price !

For example read this MSDN article

AFAI remember I think there should be a ratio of at least 7 for gained memory, because the footprint of the additionnal code for bitshifting when accessing the one-bit alignement member is really significant.

This is the wikipedia article about data alignement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜