What are bit-fields?
- Bit fields provide a mechanism to optimize memory usage by allowing to specify the exact number of bits required to store data.
- Quite useful in embedded programming like mobile phones where memory is limited.
- The declaration of bit field members follow the syntax "variable name : number of bits".
- Unnamed bit fields with width 0 are used for alignment of the next bit field to the field type boundary.
Demonstrate the usage of bit fields
#include <iostream>OUTPUT:-
#include <assert>
using namespace std;
class MyTime {
unsigned hour : 5;
unsigned mins : 6;
unsigned secs : 6;
public:
void SetHour(int aHour) {
assert ( aHour < 24 );
hour = aHour;
}
void SetMins(int aMins) {
assert ( aMins < 60 );
mins = aMins;
}
void SetSecs(int aSecs) {
assert ( aSecs < 60 );
secs = aSecs;
}
void Print() {
cout << hour << ":" << mins << ":" << secs << endl;
}
};
int main()
{
MyTime t;
t.SetHour(12);
t.SetMins(58);
t.SetSecs(23);
t.Print();
cout << "Size of MyTime = " << sizeof(t) << endl;
}
12:58:23
Size of MyTime = 4
0 comments:
Post a Comment