Reputation: 1354
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.
Upvotes: 4
Views: 376
Reputation: 63797
Saying that bit-fields has some hidden benefits is sadly quite far from the truth according to me, it would be better expressing the hidden drawbacks of their use.
To answer your question; yes, of course you can write your own algorithms to handle these bit-fields of arbitrary length as something completely different.
Though there is no method of getting the length of field m_bitfield1
(using a macro or whatever), you'll need to keep track of this yourself.
As a side note there is nothing saying that the struct below will be 1 byte in size:
struct Obj {unsigned bitfield1 : 3; unsigned bitfield2 : 5;}; // 8 bits total
This is because of potential padding after the struct, as well as in between the two fields if you are really unlucky.
C++ Standard (Draft n1905) : 9.6/1 Bit-fields
Allocation of bit-fields within a class object is implementation-defined.
Alignment of bit-fields is implementation-defined.
Read/Access to these kinds of members can also be a downfall, most compilers today can optimize these instructions to be fairly fast, though there is nothing saying that that will be the case and it can create a lot of run-time overhead if the compiler doesn't think as you do.
The order of which the bit-fields will appear in memory is also implementation defined, which can lead to unportable code that might not result in the same thing on two different systems.
C++ Standard (Draft n1905) : 9.6/1 [Note: *] Bit-fields
bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others.
Upvotes: 6
Reputation: 54600
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.
Upvotes: 9