Bit Fields in struct - C Structure

C examples for Structure:Structure Definition

Introduction

You can create a bit field in struct by placing a colon after the field name followed by the number of bits.

struct my_bits
{
  unsigned short f1 : 1;
  unsigned short f2 : 1;
  unsigned short id : 10;
} a;

Bit fields are packed as much as possible.

Demo Code

#include <stdio.h>
struct my_bits/*from   w  w  w . j  av  a  2  s . c o m*/
{
  unsigned short f1 : 1;
  unsigned short f2 : 1;
  unsigned short id : 10;
} a;

int main(void) {
  printf("%d bytes", sizeof(a)); /* "2 bytes" */
}

Result


Related Tutorials