Do bitpons have any hidden costs or benefits besides the obvious, seemingly space-saving?

this is how you declare a bit field:

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 with a specific bit size.

my question is: can I use my own algorithms to process default data types, such as integer or float, which take up a lot of unnecessary space, since the collection of smaller pieces of arbitrary size or the use of bit fields have some hidden advantages? thanks.

+4
source share
2 answers

It's good to use int as a set of bits that you access and control yourself. However, often unbiased costs use compiler-generated bit fields (and possibly your own) that you should be aware of.

+9
source

To say that bit fields have some hidden advantages, unfortunately, are far from the truth for me, it would be better to express the hidden disadvantages of their use.


To answer your question; yes, of course, you can write your own algorithms for processing these bit fields of arbitrary length as something completely different.

Although there is no way to get the length of the m_bitfield1 field (using a macro or something else), you will need to track this yourself.


As a side note, nothing is said that the structure below will be 1 byte in size:

 struct Obj {unsigned bitfield1 : 3; unsigned bitfield2 : 5;}; // 8 bits total 

This is because of potential filling after the structure, as well as between two fields, if you're really out of luck.

C ++ Standard (Draft n1905): 9.6 / 1 Bit Fields

The distribution of bit fields within a class object is determined by the implementation.

The alignment of bit fields is determined by the implementation.


Reading / Accessing these types of members can also be a fall, most compilers today can optimize these instructions to be quite fast, although there is nothing saying that this will be so, and this can create a lot of execution time overhead if the compiler does not think same as you.


The order in which bit fields appear in memory is also determined by the implementation, which may lead to unauthorized code that may not lead to the same in two different systems.

C ++ Standard (Draft n1905): 9.6 / 1 [Note: *] Bit fields

bit fields highlight distribution units on some machines, not others. Bit fields are assigned from right to left on some machines, from left to right on others.

+6
source

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


All Articles