wonderingdev
wonderingdev

Reputation: 1181

Getting negative value with bit-fields

I have a question related to bit-fields in C. Here I have such a structure:

struct Register
{
  int bit:1;
};

int main(void)
{
  struct Register bit = {1};

  printf("\nbit = %d", bit.bit);
  return 0;
}

Can you please explain me why do I get:

bit = -1

Upvotes: 1

Views: 1657

Answers (3)

Rock
Rock

Reputation: 93

cppreference: Bit-fields mentions signed bit-fields too.

signed int, for signed bit-fields (signed int b:3; has the range -4..3)

No matter unsigned int or signed int bit-fields, the programmer has the responsibility for ensuring the initialized value must be in the range.

The reason of the unexpected result of your code is well explained in the comment by haccks and Klas Lindbäck.

But let me give some examples to illustrate it.

When the bit-field size is 1, there are two possible values: either 0b0 or 0b1, which represents 0 and -1 in 2's complement respectively. As far as the field bit.bit is concerned, struct Register bit = {1}; is equivalent to bit.bit = 0b1.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

struct Register
{
  int bit:1;
};

int main()
{
    struct Register bit;

    bit.bit = 0b0;
    printf("bit = %d\n", bit.bit);

    bit.bit = 0b1;
    printf("bit = %d\n", bit.bit);

    return 0;
}

The output will be

bit = 0
bit = -1

Similarly, this is an example if the bit-field size is 2.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

struct Register
{
  int bit:2;
};

int main()
{
    struct Register bit;

    bit.bit = 0b00;
    printf("bit = %d\n", bit.bit);

    bit.bit = 0b01;
    printf("bit = %d\n", bit.bit);

    bit.bit = 0b10;
    printf("bit = %d\n", bit.bit);

    bit.bit = 0b11;
    printf("bit = %d\n", bit.bit);

    return 0;
}

The output will be

bit = 0
bit = 1
bit = -2
bit = -1

Upvotes: 1

Venkata Naidu M
Venkata Naidu M

Reputation: 351

use unsigned int , it stores 0 and 1,

struct Register
{
unsigned int bit:1;
};

int main(void)
{
 struct Register bit = {1};

 printf("\nbit = %d", bit.bit);
 return 0;
}

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

If you're working with bitfields, you should use unsigned int. signed int is a problem for bit-fields.

Upvotes: 6

Related Questions