Search code examples
cstructbit-fields

Bitfield element when read giving a different value in C


My tiny snippet when trying to write a bitfield and reading back gives a different value

#include <stdio.h>
typedef struct
{
  int a:1;
  int b:1;
  int c:1;
  int d:5;
}node_t;

int main()
{
  node_t var;
  var.a = 1;
  var.b = 0;
  int a = var.a;
  int b = var.b;
  printf(" %d", a);
  printf(" %d", b);
 return 0;
}

This gives an output:

 -1 0

How my bitfield var.a becomes -1 instead of 1?


Solution

  • You should be aware that int is signed by default. Hence, when you set one bit for the integer value, you will set the sign bit of that variable to 1. Hence it would be a negative value. To that end, it would be two's complement techniques.