Whether we like it or not, our society is money-oriented. Earning money takes time, and time has its limits; none of us has more of it. So if you want to maximize what you're earning, you must improve your speed. Bitwise operators may not always be the best choice for this, but in some cases relying on them will pay off quite handsomely.
Bitwise Operators in Action - Do You Need Them? (Page 2 of 4 )
Again, it is up to you if you can afford to do this. On the other hand, let’s pretend that you have plenty of time, so speeding up a program is something about which you're not too concerned. Now before you quit reading, thinking that nothing more is to be offered for you from this article, let me present to you the bit fields.
Bit fields are, as the name suggests, a collection of bits. You probably know that a byte at least must be used; there is no such thing as a bit type. With the help of bit fields, C/C++ lets you use memory more efficiently, as it allows you to split the memory into smaller segments. Let’s imagine you want to store data about something that has an ID that is less than 2 on the power of 12, and four true/false type properties about it.
If you create a structure for all this, you’ll waste some memory space because a short into occupies 16 bits. That’s more 4 bits more than we need. For the properties, declaring boolean types may do it, as a few compilers do a little optimizing and pack multiple bools in a single byte. If the compiler won’t do the optimizing, you’ll use 4 more bytes for the properties, besides the two for the ID.
Bit fields let us to do our own packing inside a structure. Look at the example below:
structure bitfield {
unsigned short int ID:9;
unsigned short int p_1:1;
unsigned short int p_2:1;
unsigned short int p_3:1;
unsigned short int p_4:1;
}
Now if you declare a type of this in the memory you’ll get this:
The two byte (a word) size in the memory is all we need for storing all the upper data. We can refer to any of the members of the structure in the usual way; just remember that only the structure itself will have an address, because the others are inside a byte and there is no way you can refer to it.
Of course this can also be referred to as bit packing; the memory saver has a few drawbacks also, due to the portability issue again. Bit fields may be signed or unsigned (we put the unsigned keyword in the structure for a reason; it is absolutely necessary, otherwise a signed bit may be used also). The maximum number of bits is limited to an integer, so we're talking about 2 or 4 bytes depending on the compiler.
However, if it is too large, it may be overlapped to the next memory section. Also caution is required, as bits may be stored from left to right or right to left, depending on the device. If this occurs, and somehow you still want to use the benefits of bit fields, you may use the shifting and masking technique discussed in the previous article.