Friday, June 27, 2008

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>
#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;
}
OUTPUT:-
12:58:23
Size of MyTime = 4

3 comments :

  1. hello...

    thanks this above prog lokks better 2understand,...
    but can u explain why assert required?

    ReplyDelete
    Replies
    1. assert is used to terminate the program if the condition is met.

      So in the above code, the program will terminate if aHour is greater than 24

      Delete
  2. It is worth noting that in IE8 (maybe other versions) screen.width window.screen.width and do not return the actual screen resolution, and virtual (ie, when changing the map scale changes and resolution, the return functions, for example, using Ctrl + mouse wheel)

    pay for essay

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top