Bitfields in C

Given space is often at a premium when writing applications for mobile devices, I want to show you how to use bitfields to manage a series of values that need only on/off status. The upside is that you can store a surprising number of status values within a single integer, 32 to be exact. The code that follows is pure C. Given that Objective-C is a superset of C, dont forget that you can leverage all that C has to offer, beyond working with objects.

1
2
3
4
5
6
struct

  unsigned preLoaded: 1;
  unsigned saveState: 1;
  unsigned saveLoginName: 1;
 statusFlags;

Ive defines three bitfields, all which will be saved within an unsigned integer. Accessing the bits is as easy as this:

1
2
3
4
5
6
7
// Setting bits
statusFlags.preLoaded = 1;
statusFlags.saveState = statusFlags.saveLoginName = 0;
 
// Get bits
if statusFlags.saveLoginName == 0
  ... do something here...

Using the sizeof() function, lets compare the size of an integer to the size of the structure we created:

1
2
3
4
5
6
7
8
9
10
11
12
// Setting bits
statusFlags.preLoaded = 1;
statusFlags.saveState = statusFlags.saveLoginName = 0;
 
// Get bits
if statusFlags.saveLoginName == 0
  NSLog@"saveLoginName bit is on.";
else
  NSLog@"saveLoginName bit is off.";  
 
NSLog@"Sizeof int: %d", sizeofint; 
NSLog@"Sizeof statusFlags: %d", sizeofstatusFlags;

The output looks as follows, which verifies that the bitfields are maintained within a single unsigned integer. Whats interesting is that we now know that an integer is 4 bytes, this would imply that we can store up to 32 separate flags within our structure. To verify this the case, lets create a new structure that looks as follows:

1
2
3
4
5
6
7
8
struct

  unsigned preLoaded: 1;
  unsigned saveState: 1;
  unsigned saveLoginName: 1;
  unsigned buffer: 28;
  unsigned savePassword: 1;
 statusFlagsExtended;

In this structure, buffer is nothing more than a means for me to soak up 28 bits such that I can add one more bit on the end. Lets take a look at the sizeof this structure with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Setting bits
statusFlags.preLoaded = 1;
statusFlags.saveState = statusFlags.saveLoginName = 0;
 
// Get bits
if statusFlags.saveLoginName == 0
  NSLog@"saveLoginName bit is on.";
else
  NSLog@"saveLoginName bit is off.";  
 
NSLog@"Sizeof int: %d", sizeofint; 
NSLog@"Sizeof statusFlags: %d", sizeofstatusFlags;
NSLog@"Sizeof statusFlagsExtended: %d", sizeofstatusFlagsExtended;

As expected, the structure statusFlagsExtended is also stored as an integer.

Please follow and like us:
Posted in: C

Leave a Reply

Your email address will not be published. Required fields are marked *