The problem of bit field in C Language

wdliming's Avatar, Join Date: Sep 2010
Go4Expert Member
Today ,I have learned the bit field feature of C Language in "The C Programming Language",so I search some exercise about bit field,and then I find the C Program source code below:

Code:
#include <stdio.h>

struct mybitfields
{
    unsigned short a : 4;
    unsigned short b : 5;
    unsigned short c : 7;
}test;

int main(void)
{
    int i = 0;
    test.a = 2;
    test.b = 3;
    test.c = 0;
    i = *((short *)&test);
    printf("%d",i);
    return 0;
}
After compile and run in X86,the result is 50!?I try to understand why,but I fail,so could some one tell me why and how get the result,thank you very much! ^@^
(compile environment Windows XP sp3,TDM-GCC 4.6.1,X86 architecture)
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Simple. Look at the bit field like this:
Code:
cccccccbbbbbaaaa
0000000000110010
Now work out the decimal value of 110010: 32+16+2=what?
wdliming like this
0
wdliming's Avatar, Join Date: Sep 2010
Go4Expert Member
Thank you very much! xpi0t0s!