Search code examples
cbit-fields

Does the bit field correspond to registers in the accumulator?


#include<stdio.h>
int main()
{
 struct byte
 {
 int one:1;
 };
 struct byte var = {1};
 printf("%d\n", var.one);
 return 0;
}

Things I understood:

  • : is the bit field operator. int one :1; means create variable one with memory of 1 bit.

-struct byte var = {1}; tries to put 1 in variable one.

What I did not understand

  • why the output is zero when I put struct byte var = {even_number};

  • why the output is -1 when I put struct byte var = {odd_number};

My analogy is that somehow the negative flag(7th flag) become high/1 and gives -1. But I have no proof.I think there must be some other logic. But, Does the bit field correspond to registers in the accumulator?


Solution

  • This happens because you declared the bit field as int, which is signed.

    Assuming 2's complement representation of negative numbers, that means that if the highest bit is set then the number is negative. And since the field only has 1 bit, setting this bit gives you a negative number, i.e. -1.

    If you want to store 0 or 1 in this field, you need to declare it as unsigned int and subsequently use the %u format specifier to print it.

    #include<stdio.h>
    int main()
    {
       struct byte
       {
         unsigned int one:1;
       };
       struct byte var = {1};
       printf("%u\n", var.one);
       return 0;
    }