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 120 views
120 views asked May 10, 2022 by avibootz
1 answer 131 views
1 answer 208 views
208 views asked Aug 28, 2016 by avibootz
1 answer 226 views
226 views asked Aug 28, 2016 by avibootz
2 answers 237 views
237 views asked Jan 5, 2016 by avibootz
1 answer 116 views
116 views asked Jul 3, 2024 by avibootz
1 answer 136 views
...