The most efficient way to store additional logic gates

I need to store exactly four boolean elements in my structure in c. Yes, I could use four integers or put them in an array, but I would like to make it a little better. I thought of int as "0000", where each number will be a boolean, but then when editing, I can’t edit just one digit, right? It doesn't look perfect ...

Thanks for any ideas.

+4
source share
5 answers

You can use the structure of the bit field:

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

Then you can easily edit each boolean separately, for example:

 struct foo example; example.boolean1 = 1; example.boolean2 = 0; 
+17
source

Using an int of type β€œ0000” is called using a bit field and is performed fairly regularly in practice. Yes, you can edit single values ​​using bit offsets . Personally, I would prefer to use int for the structure of the bit field, since you can expand up to 32 values ​​(if you use a 32-bit int, of course) without changing the structure.

+2
source

If you store millions, do it like packed bits.

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

If not, it does not matter.

If both of them, then you can have a serious performance tuning.

+1
source

Can be done using

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

 bool a = true; // Could also be 'bool a = 1;' 
0
source
 struct _eMyBool { int m_iOne : 1; int m_iTwo : 1; int m_iThree : 1; int m_iFour : 1; } eMyBool; 

However, do not even think that this is the most efficient way to use logical ones.

Because the extra build code generated to handle this has a price!

For example, read this MSDN article.

AFAI remember, I think that there should be a ratio of at least 7 for the acquired memory, because the trace of the additional code for bit movement when accessing the one-bit alignment element is really significant.

This is a wikipedia article on data alignment.

-1
source

Source: https://habr.com/ru/post/1334004/


All Articles