Bit fields in C ++

Rate this article




c++ bit fields, structures in c ++ for beginnersIn C ++, it is possible to set a certain number of elements of the structure in memory bits. For example, if you want to create a data structure, size corresponding register in any device. The type of element (it is called a bit field) such a structure may be an integer (most frequently of type unsigned) or enumerable (enum).

Syntax-bit field in the structure is defined as follows:
c++ bit fields, structures in c ++ for beginnersFor example:

We have determined the structure of, wherein the variables specified number will occupy bits. 2 + 2 + 4 It gives 8 bit (We lined up to size bytes). If you finish in this structure still unsigned short fifth : 5; – It will already be involved 2 bytes. The second byte would of course junk 8 – 5 = 3 bits, to be unclaimed.

Unlike associations (union) size of bit fields varies, whichever, how many bits the programmer ordered. If ordered 7 bit (say the two variables on 3 bits, and one – 1 bit), then C ++ will take one byte (8 bit) under these three variables. If the programmer will order 11 bit, then C ++ will take two bytes (16 bit). And in the second byte will be used only 5 bit, and the rest are likely to be, as useless tail. Therefore, in the description of bit fields should be considered a “alignment” to bytes. That is. distribute it as variables, so that each bit has been claimed. For alignment of memory you can use unnamed bit fields.

Here is another short example, wherein the bit fields are reserved for the date and time for the demonstration of the technology.

Result:

c++ bit fields, structures in c ++ for beginners

As you can see, bit fields store date and time. It takes this structure 6 bytes, although it is enough for five. And then there are reasons: the compiler may align withdrawn memory to an even number of bytes. For example, if we had booked 18 bit, the compiler will take us not 3 bytes, and 4, considering that the CPU likes to work with bytes, and not with bits. At least the memory or processor registers its bits prefers not, namely bytes. According to his bit: x32 feed 4 bytes, x64 has 8 bytes. Even though these bytes work is only one of them, the rest will still catch up.

Small outcome: Bit fields in structures commonly used in low-level programming, when the work is with values, able to take no bytes, and the individual bits (since, that small values).

Newsletter of programming:

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>