Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do bitfields have any hidden costs or benefits aside from the obvious seeming benefit of saving space?

Tags:

c++

bit-fields

here is how you declare a bitfield:

unsigned m_bitfield1 : 2;  // a bitfield that occupies 2 bits
unsigned m_bitfield2 : 1;  // a bitfield that occupies 1 bit

a bit-field is simply a small field that has a specific size in bits.

my question is: can i use my own algorithms to treat default data types such as integer or float that occupy lots of unnecessary space as collection of smaller parts of arbitrary size, or use of bit-fields have some hidden benefits? thank you.

like image 898
Vis Viva Avatar asked Dec 07 '22 17:12

Vis Viva


1 Answers

It is fine to use ints as a collection of bits that you access and manage yourself. However there are often un-thought-of costs to using the compiler generated bit fields (and possibly your own) that you should be aware of.

like image 106
i_am_jorf Avatar answered Feb 23 '23 00:02

i_am_jorf