How is the size of a struct with bit fields in C

1 Answer

0 votes
#include <stdio.h> 

// 32 bit = 4 bytes 

// 33 bits = 8 bytes (32 + 1)=(unsigned int + unsigned int)
typedef struct 
{
    unsigned int a:1;
    unsigned int b:31;
    unsigned int c:1;
} bits1;

// 34 bits = 8 bytes (32 + 2)=(unsigned int + unsigned int)
typedef struct 
{
    unsigned int a:1;
    unsigned int b:31;
    unsigned int c:2;
} bits2;

// 64 bits = 8 bytes (32 + 32)=(unsigned int + unsigned int)
typedef struct 
{
    unsigned int a:1;
    unsigned int b:31;
    unsigned int c:32;
} bits3;

// 65 bits = 12 bytes (32 + 32 + 1)=(unsigned int + unsigned int + unsigned int)
typedef struct 
{
    unsigned int a:2;
    unsigned int b:31;
    unsigned int c:32;
} bits4;

// 3 bits = 4 bytes (32)=(unsigned int)
typedef struct 
{
    unsigned int a:1;
    unsigned int b:1;
    unsigned int c:1;
} bits5;
   
int main(void)
{   
    bits1 b1;
    printf("%zu\n", sizeof(b1));
    
    bits2 b2;
    printf("%zu\n", sizeof(b2));
    
    bits3 b3;
    printf("%zu\n", sizeof(b3));
    
    bits4 b4;
    printf("%zu\n", sizeof(b4));
    
    bits5 b5;
    printf("%zu\n", sizeof(b5));

    return 0;
}
 
 
         
/*
run:
      
8
8
8
12
4
     
*/

 



answered Jul 3, 2024 by avibootz
edited Jul 3, 2024 by avibootz

Related questions

1 answer 128 views
128 views asked May 10, 2022 by avibootz
1 answer 141 views
1 answer 215 views
215 views asked Aug 28, 2016 by avibootz
1 answer 236 views
236 views asked Aug 28, 2016 by avibootz
2 answers 245 views
245 views asked Jan 5, 2016 by avibootz
1 answer 126 views
126 views asked Jul 3, 2024 by avibootz
1 answer 144 views
...