Thread: bitfields

  1. #1
    Registered User Tiago's Avatar
    Join Date
    Oct 2009
    Location
    Lisbon, Portugal
    Posts
    28

    bitfields

    Hi everybody...

    The following code says that the bit field has a size of 4 bytes:

    Code:
    typedef struct BitField{
    	unsigned int A:1;
    } BitField;
    
    
    int main(int argc, char *argv[]){
    	
    	printf("%d\n", sizeof(BitField));
    
    }
    And the following code says that the bit field has a size of 2 bytes (It also gives some sort of warning related to the fact that I'm using unsigned short to create a bit field):

    Code:
    typedef struct BitField{
    	unsigned short int A:1;
    } BitField;
    
    
    int main(int argc, char *argv[]){
    	
    	printf("%d\n", sizeof(BitField));
    
    }

    Finally, the following code also says that the bit field has a size of 2 bytes:

    Code:
    typedef struct BitField{
    	unsigned short int A;
    } BitField;
    
    
    int main(int argc, char *argv[]){
    	
    	printf("%d\n", sizeof(BitField));
    
    }
    So, given that I pretend to create a bit field of three int's (each with 2 bits only), using the less amount of memory possible, what is the best way to create the bit field, " unsigned int A:2; " or " unsigned short A; "?

    I'm aware that the computer can't access blocks of memory with 2 bits... but why a 1-bit unsigned int occupies more memory than an unsigned short (which has 2 bytes)?

    Thank You...

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    In a bitfield, you still need storage for the base type, whatever it is, even if you're not planning to use it all.

    EDIT: For the non-standardness, at least in C99 you can make a bitfield out of _Bool.
    Last edited by tabstop; 05-16-2010 at 09:22 AM.

  3. #3
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    Bitfields are a good solution if you want to limit your range to something under 32 bytes or to divide space into partitions. Still, the compiler will add padding at the end for example if you only use one bitfield or the sum of their sizes don't match the alignment restrictions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structure Bitfields
    By samGwilliam in forum C Programming
    Replies: 6
    Last Post: 09-04-2009, 09:45 PM
  2. Bitfields, Bit/Little Endian
    By azerej in forum C Programming
    Replies: 0
    Last Post: 05-26-2008, 02:01 AM
  3. Bitfields, Bit/Little Endian
    By plan7 in forum C Programming
    Replies: 17
    Last Post: 11-08-2007, 01:48 AM
  4. portable bitfields
    By Yarin in forum C++ Programming
    Replies: 2
    Last Post: 08-14-2007, 01:39 PM
  5. bitfields
    By Hunter2 in forum C++ Programming
    Replies: 2
    Last Post: 11-27-2002, 05:21 PM