Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print bit type as integer? How is the conversion?

Tags:

c

bit

the program is :

typedef struct xp {
        int a:2;
        int b:2;
        int c:1;
} xp;

int main(void)
{
        xp x;
        memset(&x, 0, sizeof(xp));

        x.a = 1;
        x.b = 3;
        x.c = 1;

        printf("%d\n",x.a);
        printf("%d\n",x.b);
        printf("%d\n",x.c);

        return 0;
}

I get 1 -1 -1, why? How are a, b and c stored in x? What happened when printf("%d\n",x.a); is executed?

like image 547
Fei Xue Avatar asked Aug 07 '12 23:08

Fei Xue


1 Answers

You're using a signed type for your bitfields, which means you've created what amounts to two two-bit signed integers, and one one-bit signed integer.

The possible values for a two-bit signed integer (two's complement) are: -2, -1, 0, and 1:

The possible values for a one-bit signed integer (two's complement) are -1 and 0.

By storing values that "don't fit", like you have done in these lines:

x.b = 3;
x.c = 1;

You will get strange behaviour as the bit patterns you store are interpreted differently when read. You can have a similar experience by doing something like:

char x = 58147;

on a machine with an 8-bit char type, that value won't fit, so you'll read something different back when accessing x.

like image 50
Carl Norum Avatar answered Oct 01 '22 20:10

Carl Norum