Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   The problem of bit field in C Language (http://www.go4expert.com/forums/bit-field-c-language-t28026/)

wdliming 15Mar2012 17:34

The problem of bit field in C Language
 
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)

xpi0t0s 16Mar2012 00:09

Re: The problem of bit field in C Language
 
Simple. Look at the bit field like this:
Code:

cccccccbbbbbaaaa
0000000000110010

Now work out the decimal value of 110010: 32+16+2=what?

wdliming 16Mar2012 08:58

Re: The problem of bit field in C Language
 
Thank you very much! xpi0t0s!


All times are GMT +5.5. The time now is 21:31.